1 package com.atlassian.sal.core.executor;
2
3 import com.atlassian.sal.api.executor.ThreadLocalDelegateExecutorFactory;
4
5 import java.util.concurrent.Executor;
6 import java.util.concurrent.Callable;
7 import java.util.concurrent.ExecutorService;
8 import java.util.concurrent.ScheduledExecutorService;
9
10 /**
11 * Creates delegating executable classes that copy thread local state
12 */
13 public class DefaultThreadLocalDelegateExecutorFactory implements ThreadLocalDelegateExecutorFactory
14 {
15 private final ThreadLocalContextManager manager;
16
17 protected DefaultThreadLocalDelegateExecutorFactory(ThreadLocalContextManager manager)
18 {
19 this.manager = manager;
20 }
21
22 /**
23 * Creates an executor that ensures the executed delegate instance runs in the same thread local context as the calling
24 * code.
25 *
26 * @param delegate The Executor instance to delegate to
27 * @return The wrapping executor that manages thread local state transfer
28 */
29 public Executor createExecutor(Executor delegate)
30 {
31 return new ThreadLocalDelegateExecutor(manager, delegate);
32 }
33
34 /**
35 * Creates an executor service that ensures the executed delegate instance runs in the same thread local context as the
36 * calling code.
37 *
38 * @param delegate The ExecutorService instance to delegate to
39 * @return The wrapping ExecutorService that manages thread local state transfer
40 */
41 public ExecutorService createExecutorService(ExecutorService delegate)
42 {
43 return new ThreadLocalDelegateExecutorService(manager, delegate);
44 }
45
46 /**
47 * Creates a scheduled executor service that ensures the executed delegate instance runs in the same thread local
48 * context as the calling code.
49 *
50 * @param delegate The ScheduledExecutorService instance to delegate to
51 * @return The wrapping ScheduledExecutorService that manages thread local state transfer
52 */
53 public ScheduledExecutorService createScheduledExecutorService(ScheduledExecutorService delegate)
54 {
55 return new ThreadLocalDelegateScheduledExecutorService(manager, delegate);
56 }
57
58 /**
59 * Creates a runnable that ensures the executed runnable instance runs in the same thread local context as the calling
60 * code
61 *
62 * @param delegate The runnable to delegate to
63 * @return The wrapping Runnable that manages thread local state transfer
64 */
65 public Runnable createRunnable(Runnable delegate)
66 {
67 return new ThreadLocalDelegateRunnable(manager, delegate);
68 }
69
70 /**
71 * Creates a callable that ensures the executed runnable instance runs in the same thread local context as the calling
72 * code.
73 *
74 * @param delegate The callable to delegate to
75 * @param <T> The type that the callable returns
76 * @return The wrapping Callable that manages thread local state transfer
77 */
78 public <T> Callable<T> createCallable(Callable<T> delegate)
79 {
80 return new ThreadLocalDelegateCallable<T>(manager, delegate);
81 }
82 }