I have a Thread sub-class called XmlProcessor that needs to accept some list or array of Strings to process. I need this list to be completely private to each thread, so that it isn't modified in any way by other threads. What is my best option?
Thanks, Ja开发者_JAVA技巧red
Use the ThreadLocal class. It allows you to create references visible only by the current thread.
If there is an instance of XmlProcessor per thread and the list is held as a private, it should be accessible from other threads so long as you: 1. don't provider a getter or setter method 2. ensure that the reference held by the instance is a copy of whatever was passed rather than just a pointer to the list that might be held by other objects.
You might consider using Guava's ImmutableList class to enforce this if the list cannot be changed.
http://docs.guava-libraries.googlecode.com/git-history/release09/javadoc/index.html
Based on Jareds comment it seems you have something that looks like this.
public class MyClass extends Runnable{
static ThreadLocal<List<String>> listBonds = new ThreadLocal<List<String>>();
public MyClass (List<String> list){
listBonds.set(list);
}
public void run(){
listBonds.get(); // it returns null here?
}
}
If my assumption is true then the reason listBonds.get() is null is because a different thread is accessing listBonds when you invoke set
to when you invoke get
Image this
Thread 1:
Thread myClass = new Thread(new MyClass(someList));
listBonds.set(someList);
myClass.start();
Thread 2: (MyClass)
listBonds.get() --- A new thread is requesting the threadlocal variable and hence its null
If this is the case then the Runnable instance will be inherently thread-local/thread-safe and then you can have the List be an instance variable of the Runnable
精彩评论