1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package com.google.common.util.concurrent;
18
19 import com.google.common.base.Supplier;
20 import com.google.common.base.Suppliers;
21
22 import junit.framework.TestCase;
23
24 import java.security.Permission;
25 import java.util.concurrent.Callable;
26
27
28
29
30
31
32 public class CallablesTest extends TestCase {
33
34 public void testReturning() throws Exception {
35 assertNull(Callables.returning(null).call());
36
37 Object value = new Object();
38 Callable<Object> callable = Callables.returning(value);
39 assertSame(value, callable.call());
40
41 assertSame(value, callable.call());
42 }
43
44 public void testRenaming() throws Exception {
45 String oldName = Thread.currentThread().getName();
46 final Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
47 Callable<Void> callable = new Callable<Void>() {
48 @Override public Void call() throws Exception {
49 assertEquals(Thread.currentThread().getName(), newName.get());
50 return null;
51 }
52 };
53 Callables.threadRenaming(callable, newName).call();
54 assertEquals(oldName, Thread.currentThread().getName());
55 }
56
57 public void testRenaming_exceptionalReturn() throws Exception {
58 String oldName = Thread.currentThread().getName();
59 final Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
60 class MyException extends Exception {}
61 Callable<Void> callable = new Callable<Void>() {
62 @Override public Void call() throws Exception {
63 assertEquals(Thread.currentThread().getName(), newName.get());
64 throw new MyException();
65 }
66 };
67 try {
68 Callables.threadRenaming(callable, newName).call();
69 fail();
70 } catch (MyException expected) {}
71 assertEquals(oldName, Thread.currentThread().getName());
72 }
73
74 public void testRenaming_noPermissions() throws Exception {
75 System.setSecurityManager(new SecurityManager() {
76 @Override public void checkAccess(Thread t) {
77 throw new SecurityException();
78 }
79 @Override public void checkPermission(Permission perm) {
80
81 }
82 });
83 try {
84 final String oldName = Thread.currentThread().getName();
85 Supplier<String> newName = Suppliers.ofInstance("MyCrazyThreadName");
86 Callable<Void> callable = new Callable<Void>() {
87 @Override public Void call() throws Exception {
88 assertEquals(Thread.currentThread().getName(), oldName);
89 return null;
90 }
91 };
92 Callables.threadRenaming(callable, newName).call();
93 assertEquals(oldName, Thread.currentThread().getName());
94 } finally {
95 System.setSecurityManager(null);
96 }
97 }
98 }