• Post Reply Bookmark Topic Watch Topic
  • New Topic

How control calling threads instances of same variable in Singleton?  RSS feed

 
Robert Paris
Ranch Hand
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a VM-wide Singleton. In this singleton I have a variable (or property) that is set by calling threads. I want the following:
1. When a calling thread sets it, that value is visible only to that calling thread (or rather within the singleton only when called by that thread) and all the sub-threads it spawns
2. Every calling thread (to the singleton's method) gets a separate instance (although all sub-threads of that calling thread are also considered to be of the same thread)
What is the best/most-accurate(?) way to do this?
As a quick example of something like what I'm talking about:
imagine a variable "currentCaller". Let's say this is set by calling MySingleton.setCaller() (this method may or may not be static - any recommendations?) If Thread "A" sets it to "John" then every time Thread "A" or any threads under Thread "A" call any method on MySingleton, it will know to use currentUser=John. At the same time, Thread "B" sets it to "Joe" and it should be Joe for all it's calls.
Thanks!
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sounds like what you want is ThreadLocal.
 
Robert Paris
Ranch Hand
Posts: 585
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, but how exactly is that going to work? Let's say I have the following:

I want Thread A and B to have diff. values for that ThreadLocal variable. However, I would like to have Thread B1 and B2 to have the same as Thread B. In other words, every thread that is the child of the main thread is considered a new thread. Every thread under those threads inherit from the parent which is directly under the main thread. Is there a best way to do this?
I assumed orginally I wanted InheritableThreadLocal, but how do I make sure it's inheritable only from the child under "main" downwards and not that everything shares the same (i.e. if they inherited from "main" thread)?
 
David Weitzman
Ranch Hand
Posts: 1365
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Look at what this code does. Some variant of it may meet your needs. Note that the call to threadLocal.get() in the main thread is very important, because otherwise the child threads of main will just get a null initial value:

Outputs something similar to this:

[ March 20, 2004: Message edited by: David Weitzman ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!