1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v2.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  
15  package ch.qos.logback.core.util;
16  
17  import ch.qos.logback.core.Context;
18  import ch.qos.logback.core.spi.ContextAwareBase;
19  
20  /**
21   * Allows masking of interrupt flag if previously the flag is already set. Does
22   * nothing otherwise.
23   * 
24   * Typical use:
25   * 
26   * <pre>
27   * InterruptUtil interruptUtil = new InterruptUtil(context);
28   * 
29   * try {
30   *     interruptUtil.maskInterruptFlag();
31   *     someOtherThread.join(delay);
32   * } catch (InterruptedException e) {
33   *     // reachable only if join does not succeed within delay.
34   *     // Without the maskInterruptFlag() call, the join() would have returned
35   *     // immediately
36   *     // had the current thread been interrupted previously, i.e. before entering
37   *     // the above block
38   * } finally {
39   *     interruptUtil.unmaskInterruptFlag();
40   * }
41   * </pre>
42   * 
43   * @author Ceki Gulcu
44   * @since 1.2.2
45   */
46  public class InterruptUtil extends ContextAwareBase {
47  
48      final boolean previouslyInterrupted;
49  
50      public InterruptUtil(Context context) {
51          super();
52          setContext(context);
53          previouslyInterrupted = Thread.currentThread().isInterrupted();
54      }
55  
56      public void maskInterruptFlag() {
57          if (previouslyInterrupted) {
58              Thread.interrupted();
59          }
60      }
61  
62      public void unmaskInterruptFlag() {
63          if (previouslyInterrupted) {
64              try {
65                  Thread.currentThread().interrupt();
66              } catch (SecurityException se) {
67                  addError("Failed to interrupt current thread", se);
68              }
69          }
70      }
71  
72  }