|
| 1 | +package chapter4; |
| 2 | + |
| 3 | +import java.text.ParseException; |
| 4 | +import java.text.SimpleDateFormat; |
| 5 | +import java.util.Date; |
| 6 | +import java.util.concurrent.CountDownLatch; |
| 7 | +import java.util.concurrent.ExecutorService; |
| 8 | +import java.util.concurrent.Executors; |
| 9 | + |
| 10 | +/** |
| 11 | + * Created by 13 on 2017/5/6. |
| 12 | + */ |
| 13 | +public class ThreadLocalDemo_GC { |
| 14 | + static volatile ThreadLocal<SimpleDateFormat> threadLocal = new ThreadLocal<SimpleDateFormat>() { |
| 15 | + protected void finalize() throws Throwable { |
| 16 | + System.out.println(this.toString() + " is gc"); |
| 17 | + } |
| 18 | + }; |
| 19 | + |
| 20 | + static volatile CountDownLatch countDownLatch = new CountDownLatch(100); |
| 21 | + |
| 22 | + public static class ParseDate implements Runnable { |
| 23 | + int i = 0; |
| 24 | + |
| 25 | + public ParseDate(int i) { |
| 26 | + this.i = i; |
| 27 | + } |
| 28 | + |
| 29 | + @Override |
| 30 | + public void run() { |
| 31 | + |
| 32 | + try { |
| 33 | + if (threadLocal.get() == null) { |
| 34 | + threadLocal.set(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") { |
| 35 | + protected void finalize() throws Throwable { |
| 36 | + System.out.println(this.toString() + " is gc"); |
| 37 | + } |
| 38 | + }); |
| 39 | + System.out.println(Thread.currentThread().getId() + " create SimpleDatFormat"); |
| 40 | + } |
| 41 | + Date date = threadLocal.get().parse("2017-05-06 12:33:" + i % 60); |
| 42 | + System.out.println(i + ":" + date); |
| 43 | + } catch (ParseException e) { |
| 44 | + e.printStackTrace(); |
| 45 | + } finally { |
| 46 | + countDownLatch.countDown(); |
| 47 | + } |
| 48 | + |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + |
| 53 | + public static void main(String args[]) throws InterruptedException { |
| 54 | + ExecutorService executorService = Executors.newFixedThreadPool(10); |
| 55 | + for (int i = 0; i < 100; i++) { |
| 56 | + executorService.execute(new ParseDate(i)); |
| 57 | + } |
| 58 | + countDownLatch.await(); |
| 59 | + |
| 60 | + System.out.println("mission complete!"); |
| 61 | + |
| 62 | + threadLocal = null; |
| 63 | + System.gc(); |
| 64 | + System.out.println("first GC complete!!"); |
| 65 | + |
| 66 | + threadLocal = new ThreadLocal<SimpleDateFormat>(); |
| 67 | + |
| 68 | + countDownLatch = new CountDownLatch(100); |
| 69 | + |
| 70 | + for (int i = 0; i < 100; i++) { |
| 71 | + executorService.execute(new ParseDate(i)); |
| 72 | + } |
| 73 | + |
| 74 | + countDownLatch.await(); |
| 75 | + Thread.sleep(1000); |
| 76 | + System.gc(); |
| 77 | + System.out.println("second GC complete!"); |
| 78 | + } |
| 79 | +} |
0 commit comments