0

I have a multi threaded application but there is one data member that needs to be accessed by many of the classes in the thread.

This data member would have a different value for each thread, but I want to access it without having to pass it as a parameter.

How can this be done in Java?

Arya
  • 8,473
  • 27
  • 105
  • 175
  • 9
    Look into thread locals. – Sotirios Delimanolis Jun 09 '15 at 03:39
  • @SotiriosDelimanolis If I make a threadlocal datamember 'static' so I can access it from other classes. Would that be a problem? – Arya Jun 09 '15 at 03:56
  • Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist). Check this ---> http://stackoverflow.com/questions/817856/when-and-how-should-i-use-a-threadlocal-variable – Am_I_Helpful Jun 09 '15 at 03:58

1 Answers1

0

I agree with the comment suggestion to use ThreadLocal. I think this program illustrates the sort of use you want:

public class Test implements Runnable {
  public static ThreadLocal<String> myString = new ThreadLocal<String>();
  private String myInitialString;
  public Test(String someString) {
    myInitialString = someString;
  }

  public void run() {
    myString.set(myInitialString);
    System.out.println(myString.get());
    myString.set(myString.get() + " changed");
    System.out.println(myString.get());
    new OtherTest().printTheString();
  }

  public static void main(String[] args) throws InterruptedException {
    Thread[] threads = new Thread[3];
    for (int i = 0; i < threads.length; i++) {
      threads[i] = new Thread(new Test("Thread" + i));
      threads[i].start();
    }
    for (int i = 0; i < threads.length; i++) {
      threads[i].join();
    }
  }
}

class OtherTest{
  public void printTheString(){
    System.out.println(Test.myString.get()+" OtherTest");
  }
}

Typical output (the order varies from run to run):

Thread0
Thread2
Thread2 changed
Thread1
Thread0 changed
Thread1 changed
Thread1 changed OtherTest
Thread0 changed OtherTest
Thread2 changed OtherTest
Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75