1 |
tim |
1.1 |
/* |
2 |
|
|
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
|
|
* Expert Group and released to the public domain. Use, modify, and |
4 |
|
|
* redistribute this code in any way without acknowledgement. |
5 |
|
|
*/ |
6 |
|
|
|
7 |
|
|
package java.util.concurrent; |
8 |
|
|
|
9 |
|
|
import java.security.AccessControlContext; |
10 |
|
|
import java.security.AccessControlException; |
11 |
|
|
import java.security.AccessController; |
12 |
|
|
import java.security.PrivilegedAction; |
13 |
|
|
|
14 |
|
|
/** |
15 |
|
|
* A {@link FutureTask} that executes with the given (or current, if |
16 |
|
|
* not specified) access control context and/or the given (or current) |
17 |
|
|
* context class loader. |
18 |
|
|
* |
19 |
|
|
* @since 1.5 |
20 |
|
|
* @author Doug Lea |
21 |
|
|
*/ |
22 |
|
|
public class PrivilegedFutureTask<T> extends FutureTask<T> { |
23 |
|
|
|
24 |
|
|
/** |
25 |
|
|
* Constructs a <tt>PrivilegedFutureTask</tt> that will, upon running, |
26 |
|
|
* execute the given <tt>Callable</tt> under the current access control |
27 |
|
|
* context, with the current context class loader as the context class |
28 |
|
|
* loader. |
29 |
|
|
* |
30 |
|
|
* @throws AccessControlException if the current access control context |
31 |
|
|
* does not have permission to both set and get context class loader. |
32 |
|
|
*/ |
33 |
|
|
public PrivilegedFutureTask(Callable<T> task) { |
34 |
|
|
super(task); |
35 |
tim |
1.2 |
this.ccl = Thread.currentThread().getContextClassLoader(); |
36 |
|
|
this.acc = AccessController.getContext(); |
37 |
|
|
|
38 |
|
|
acc.checkPermission(new RuntimePermission("getContextClassLoader")); |
39 |
|
|
acc.checkPermission(new RuntimePermission("setContextClassLoader")); |
40 |
tim |
1.1 |
} |
41 |
|
|
|
42 |
|
|
|
43 |
|
|
public void run() { |
44 |
tim |
1.2 |
AccessController.doPrivileged(new PrivilegedAction() { |
45 |
|
|
public Object run() { |
46 |
|
|
runPrivileged(); |
47 |
|
|
return null; |
48 |
|
|
} |
49 |
|
|
}, acc); |
50 |
tim |
1.1 |
} |
51 |
|
|
|
52 |
|
|
|
53 |
|
|
private void runPrivileged() { |
54 |
|
|
ClassLoader saved = null; |
55 |
tim |
1.2 |
try { |
56 |
tim |
1.1 |
ClassLoader current = Thread.currentThread().getContextClassLoader(); |
57 |
|
|
if (ccl != current) { |
58 |
|
|
Thread.currentThread().setContextClassLoader(ccl); |
59 |
|
|
saved = current; |
60 |
|
|
} |
61 |
|
|
super.run(); |
62 |
|
|
} |
63 |
|
|
finally { |
64 |
|
|
if (saved != null) |
65 |
|
|
Thread.currentThread().setContextClassLoader(saved); |
66 |
|
|
} |
67 |
|
|
} |
68 |
|
|
|
69 |
|
|
private final ClassLoader ccl; |
70 |
|
|
private final AccessControlContext acc; |
71 |
|
|
} |
72 |
|
|
|