-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathThreadLocalDemo_Gc.java
More file actions
63 lines (58 loc) · 2.03 KB
/
Copy pathThreadLocalDemo_Gc.java
File metadata and controls
63 lines (58 loc) · 2.03 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
58
59
60
61
62
63
package ch4.s3;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadLocalDemo_Gc {
static volatile ThreadLocal<SimpleDateFormat> t1 =new ThreadLocal<SimpleDateFormat>(){
protected void finalize() throws Throwable {
System.out.println(this.toString() + " is gc");
}
};
static volatile CountDownLatch cd =new CountDownLatch(10000);
public static class ParseDate implements Runnable{
int i=0;
public ParseDate(int i){
this.i = i;
}
public void run() {
try{
if(t1.get()==null){
t1.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"){
protected void finalize() throws Throwable {
System.out.println(this.toString() + " is gc");
}
});
System.out.println(Thread.currentThread().getId() + ":create SimpleDateFormat");
}
Date t =t1.get().parse("2015-03-29 19:29:"+i%60);
} catch (ParseException e) {
e.printStackTrace();
} finally {
cd.countDown();
}
}
}
public static void main(String []args) throws InterruptedException {
ExecutorService es = Executors.newFixedThreadPool(10);
for(int i=0;i<10000;i++){
es.execute(new ParseDate(i));
}
cd.wait();
System.out.println("mission complete!!");
t1=null;
System.gc();
System.out.println("first GC complete!!");
t1= new ThreadLocal<SimpleDateFormat>();
cd =new CountDownLatch(10000);
for(int i=0;i<10000;i++){
es.execute(new ParseDate(i));
}
cd.wait();
Thread.sleep(1000);
System.gc();
System.out.println("second GC complete!!");
}
}