View Javadoc
1   package com.atlassian.sal.core.executor;
2   
3   import com.atlassian.sal.api.executor.ThreadLocalDelegateExecutorFactory;
4   
5   import javax.annotation.Nonnull;
6   import javax.annotation.ParametersAreNonnullByDefault;
7   import java.util.concurrent.Callable;
8   import java.util.concurrent.ScheduledExecutorService;
9   import java.util.concurrent.ScheduledFuture;
10  import java.util.concurrent.TimeUnit;
11  
12  import static com.google.common.base.Preconditions.checkNotNull;
13  
14  /**
15   * Scheduled executor service that wraps executing callables and runnables in a wrapper that transfers the thread local
16   * state of the caller to the thread of the executing task.
17   *
18   * @since 2.0
19   */
20  @ParametersAreNonnullByDefault
21  public class ThreadLocalDelegateScheduledExecutorService extends ThreadLocalDelegateExecutorService implements ScheduledExecutorService {
22      private final ScheduledExecutorService delegate;
23      private final ThreadLocalDelegateExecutorFactory deletegateExecutorFactory;
24  
25      public ThreadLocalDelegateScheduledExecutorService(ScheduledExecutorService delegate,
26                                                         ThreadLocalDelegateExecutorFactory deletegateExecutorFactory) {
27          super(delegate, deletegateExecutorFactory);
28          this.delegate = checkNotNull(delegate);
29          this.deletegateExecutorFactory = checkNotNull(deletegateExecutorFactory);
30      }
31  
32      @Override
33      @Nonnull
34      public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
35          return delegate.schedule(deletegateExecutorFactory.createRunnable(command), delay, unit);
36      }
37  
38      @Override
39      @Nonnull
40      public <V> ScheduledFuture<V> schedule(Callable<V> callable, long delay, TimeUnit unit) {
41          return delegate.schedule(deletegateExecutorFactory.createCallable(callable), delay, unit);
42      }
43  
44      @Override
45      @Nonnull
46      public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
47          return delegate.scheduleAtFixedRate(deletegateExecutorFactory.createRunnable(command), initialDelay, period, unit);
48      }
49  
50      @Override
51      @Nonnull
52      public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) {
53          return delegate.scheduleWithFixedDelay(deletegateExecutorFactory.createRunnable(command), initialDelay, delay, unit);
54      }
55  }