Skip to main content

Specity thread to threadlocal

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
2 replies [Last post]
zscipio
Offline
Joined: 2008-11-08

I am setting a value in a threadlocal variable "id" in the class "MyThreadLocal" in the thread "main".

A class is being executed in a different thread "sub".

It want to access the value of the variable "id" in thread "main". But I can't figure out how to specify the thread to the method get() within the threadlocal variable "id" of class "MythreadLocal". The specs say the get() uses the current thread.

My intent was to have global variables that could be used by any class in a process. Threadlocal works fine if the process is single threaded but if the process is multi-threaded Threadlocal doesn't seem to work. Does anyone know how to have global values through-out a process?

Thank you,

Zscipio

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
rbk
Offline
Joined: 2003-08-26

Zscipio,

Just use a static if you want a truely global variable. ThreadLocal is, as it names suggests, for making globally scoped variables local to a thread.

Regards

Richard

zscipio
Offline
Joined: 2008-11-08

Thank you for your answer.

I don't understand.

If a class has a variable in it and the class is used from a different thread the variable is null. Of course I may be missing something. Could you say your answer in a different way?