Is it possible to have a unique static variable in a thread?
I have a static variable that I would like to be unique for each thread.
Is this the case for all static variables? Or it cannot be guaranteed. That is, will threads sometimes update the value of a static variable in main memory, or store it in themselves?
If this cannot be guaranteed, is there any variable type in Java that is both static and thread-unique? Something essentially global to a thread, but hidden from other threads?
source to share
I think you are looking for Java ThreadLocal .
This class provides thread local variables. These variables differ from their regular counterparts in that each thread that accesses one (through its getter or setter) has its own, independently initialized copy of the variable.
Keep in mind that if you are doing a thread pool this can get you in trouble as you might think you are getting a new thread in terms of starting a new process, but what happens is that you are reusing the thread that ended up with others the data and therefore have leftovers and are difficult to debug when they occur in the wild.
Here's a tutorial on using ThreadLocal.
source to share
static
variables are shared across threads.
If you want your variable to be unique for each thread, you can use ThreadLocal
:
// Atomic integer containing the next thread ID to be assigned
private static final AtomicInteger nextId = new AtomicInteger(0);
// Thread local variable containing each thread ID
private static final ThreadLocal<Integer> threadId =
new ThreadLocal<Integer>() {
@Override protected Integer initialValue() {
return nextId.getAndIncrement();
}
};
source to share