• Post Reply Bookmark Topic Watch Topic
  • New Topic

Multiple instances - single jvm - global variable  RSS feed

 
Roger Nelson
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am working on an application that spawn multiple instances(using threads) within a single JVM where you cannot use static references for global variables, since all instance will be using the same variable.
The solution would be to introduce an intermediate class that holds a key - value pair to distinguish the exact variable related to an instance.
But still the limitation is that each class within the instance has to aware of the key. This means the key has to be passed to each constructor in a class.
Is there any solution available by which one does not require the key to be passed to each and every object in the constructor???
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two different solutions.

One is to use thread-local variables: see java.lang.ThreadLocal. These are very cool if they apply to your problem. Basically, the effect you can get is like static variables that have different values depending on which thread reads them.

The other is to use separate ClassLoaders for each instance. If the same class is loaded twice by two different ClassLoaders, it's as if it's two separate classes; each one has its own set of static variables.

The first of these two is easier but more restrictive. The second is harder but lets you do more. I'd be happy to provide more details once you decide what you want to do.
 
Roger Nelson
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks! for the response, this was exactly what I was looking for.

ThreadLocal variables looks good, for applications where the main thread spawn multiple threads and acquires a unique variable for each thread.But if any of the spawned thread have a child thread, then the new child thread acquires a different variable.
I am looking for a solution where the same variable is accessed by any first level threads and their child threads, and therefore the class loader solution looks more appealing.
If possible can you provide some information regarding why the classloader solution tends to be difficult to implement, and is there any limitations to it.
Thanks!
 
Roger Nelson
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok, I have come across InheritableThreadLocal which passes on values to child threads.
anyway the classloader solution still looks more promising :-)
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!