[英]UUID.randomUUID within ThreadLocal
I am looking at the following method and I am wondering if putting UUID.randomUUID()
within ThreadLocal
makes any sense or will not introduce an unintentional overhead:我正在查看以下方法,我想知道将
UUID.randomUUID()
放在ThreadLocal
中是否有意义或不会引入无意的开销:
class UUIDUtil {
// TODO: why putting randomUUID into ThreadLocal? Will this avoid contentions?
public static final ThreadLocal<UUID> generator =
ThreadLocal.withInitial(UUID::randomUUID);
}
Should I leave randomUUID
within a ThreadLocal
?我应该在
ThreadLocal
保留randomUUID
吗? And if so, why?如果是这样,为什么?
Does putting UUID in ThreadLocal avoids contention if multiple threads want to generate a UUID at the same time?如果多个线程要同时生成 UUID,将 UUID 放入 ThreadLocal 是否可以避免争用?
When you have a look to the JavaDoc for ThreadLocal, you will find there some sample code that can be used to give each Thread a unique number (the original thread id will be reused!!).当您查看 ThreadLocal 的 JavaDoc 时,您会发现一些示例代码可用于为每个线程提供唯一编号(原始线程 ID 将被重用!!)。
With your code here, you will give each thread a unique id in the form of a UUID.使用此处的代码,您将以 UUID 的形式为每个线程提供一个唯一的 ID。 And that has to be stored inside a ThreadLocal instance …
这必须存储在 ThreadLocal 实例中......
If that makes sense is a different story, but it can be useful for logging purposes, as it allows you to distinguish the threads more clearly as with the thread id only.如果这有意义则另当别论,但它可用于记录目的,因为它允许您像仅使用线程 id 一样更清楚地区分线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.