为什么方法中的局部变量会被提前垃圾回收?
为什么方法中的局部变量会被提前垃圾回收?
这是一个多线程测试代码,每次创建一个新的newSingleThreadExecutor,并且还有两个其他的线程不断触发垃圾回收。在HotSpot java8 (1.8.0_221)下,会出现线程池已关闭的错误。\n运行一段时间后,你将会得到以下错误:\n“Exception in thread \"Thread-2\" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@a5acd19 rejected from java.util.concurrent.ThreadPoolExecutor@30890a38[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]\nat java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)\nat java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)\nat java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)\nat java.util.concurrent.Executors$DelegatedExecutorService.execute(Executors.java:668)\nat ThreadPoolTest.submit(ThreadPoolTest.java:54)\nat ThreadPoolTest$1.run(ThreadPoolTest.java:12)\nat java.lang.Thread.run(Thread.java:748)”\nExecutors.newSingleThreadExecutor创建的是一个自动关闭的线程池(java.util.concurrent.Executors.FinalizableDelegatedExecutorService),因此它应该在对象被收集之前执行关闭。\n但从错误日志中可以看出,executorService被提前关闭了。就好像在堆栈帧弹出之前,executorService的finalize方法被提前执行了。\n为什么会发生这种情况呢?