View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.util.thread;
20  
21  /**
22   * Marker that wraps a Runnable, indicating that it is running in a thread that must not be blocked.
23   * <p />
24   * Client code can use the thread-local {@link #isNonBlockingThread()} to detect whether they are
25   * in the context of a non-blocking thread, and perform different actions if that's the case.
26   */
27  public class NonBlockingThread implements Runnable
28  {
29      private final static ThreadLocal<Boolean> __nonBlockingThread = new ThreadLocal<>();
30  
31      /**
32       * @return whether the current thread is a thread that must not block.
33       */
34      public static boolean isNonBlockingThread()
35      {
36          return Boolean.TRUE.equals(__nonBlockingThread.get());
37      }
38  
39      private final Runnable delegate;
40  
41      public NonBlockingThread(Runnable delegate)
42      {
43          this.delegate = delegate;
44      }
45  
46      @Override
47      public void run()
48      {
49          try
50          {
51              __nonBlockingThread.set(Boolean.TRUE);
52              delegate.run();
53          }
54          finally
55          {
56              __nonBlockingThread.remove();
57          }
58      }
59  }