Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have a static variable unique per thread?

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?

like image 481
stuart Avatar asked Nov 28 '22 07:11

stuart


1 Answers

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.

like image 132
Sled Avatar answered Dec 05 '22 11:12

Sled