I have a static variable that I would like to be unique per thread.
Is this the case for all static variables? Or can it not be guaranteed. That is, will threads occasionally update the static variable's value in the main memory, or keep it to themselves?
If this cannot be guaranteed, is there any type of variable in Java that is both static and thread-unique? Something essentially global to a thread, but hidden from other threads?
I think what you are looking for is Java's ThreadLocal.
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its get or set method) has its own, independently initialized copy of the variable.
Mind you, if you do thread pooling this may cause problems for you since you may think you are getting a new thread, in terms of it starting a new process, but what is happening is that you are reusing a thread that finished working on other data and thus has left-overs and these are hard to debug when they occur in the wild.
Here is a tutorial on using ThreadLocal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With