Java缓存线程池和线程本地 [英] Java Cached thread pool and thread local

查看:277
本文介绍了Java缓存线程池和线程本地的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于java和并发性的问题。

I have a question about java and concurrency.

假设我有一个ThreadLocal变量。我使用CachedThreadPool来获取新线程。
当线程被重用时,ThreadLocal变量发生了什么?

Let say I have a ThreadLocal variable called a. And I use a CachedThreadPool to obtain new threads. When a thread is rehused, what happends to the ThreadLocal variable? it mantains the same value (cause it is a the same thread) or it starts empty (as if the thread was new)?

感谢

推荐答案

默认情况下,ThreadLocals和线程一起被重用。如果您需要重新初始化它们,可以覆盖以下方法:

By default ThreadLocals are reused along with the thread. If you need them to be be reinitialized you can do so by overriding the methods noted below:

javadoc for java.util.concurrent.ThreadPoolExecutor


Hook方法
此类提供受保护的overridable beforeExecute(java.lang.Thread,java.lang.Runnable)和afterExecute(java.lang.Runnable,java.lang.Throwable )方法,它们在每个任务执行之前和之后调用。这些可以用于操纵执行环境;例如,重新初始化ThreadLocals,收集统计信息或添加日志条目。此外,方法terminate()可以被覆盖以执行任何需要在执行器完全终止时执行的特殊处理。
如果钩子或回调方法抛出异常,内部工作线程可能会失败并突然终止。

Hook methods This class provides protected overridable beforeExecute(java.lang.Thread, java.lang.Runnable) and afterExecute(java.lang.Runnable, java.lang.Throwable) methods that are called before and after execution of each task. These can be used to manipulate the execution environment; for example, reinitializing ThreadLocals, gathering statistics, or adding log entries. Additionally, method terminated() can be overridden to perform any special processing that needs to be done once the Executor has fully terminated. If hook or callback methods throw exceptions, internal worker threads may in turn fail and abruptly terminate.

这篇关于Java缓存线程池和线程本地的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆