forked from jbloch/effective-java-3e-source-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadLocalExp.java
More file actions
57 lines (49 loc) · 1.95 KB
/
Copy pathThreadLocalExp.java
File metadata and controls
57 lines (49 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package effectivejava.threadlocal;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadLocalExp {
public static class MyRunnable implements Runnable
{
// Initially value as 0
AtomicInteger val
= new AtomicInteger(0);
private ThreadLocal<Integer> threadLocal =
new ThreadLocal<Integer>();
private ThreadLocal<Integer> threadLocalINT = ThreadLocal.withInitial(() -> {
return Integer.valueOf((int) (Math.random() * 80D));
});
private ThreadLocal threadLocalOverridInitialValue = new ThreadLocal<Integer>() {
@Override protected Integer initialValue()
{
return val.getAndIncrement();
}
};
@Override
public void run() {
threadLocal.set( (int) (Math.random() * 50D) );
try
{
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println("threadLocal: " + threadLocal.get());
System.out.println("threadLocalINT: " + threadLocalINT.get());
System.out.println("threadLocalOverridInitialValue: " + threadLocalOverridInitialValue.get());
System.out.println("After removing thread locals");
threadLocal.remove();
threadLocalINT.remove();
threadLocalOverridInitialValue.remove();
System.out.println("threadLocal: " + threadLocal.get());
System.out.println("threadLocalINT: " + threadLocalINT.get());
System.out.println("threadLocalOverridInitialValue: " + threadLocalOverridInitialValue.get());
}
}
public static void main(String[] args)
{
MyRunnable runnableInstance = new MyRunnable();
Thread t1 = new Thread(runnableInstance);
Thread t2 = new Thread(runnableInstance);
// this will call run() method
t1.start();
t2.start();
}
}