I have a class Cache
which picks up List<SomeObject> someObjectList
from DB and stores it in static variable.
Now I have another thread A which uses this List as follows
class A extends Thread{
private List<SomeObject> somobjLst;
public A(){
somobjLst = Cache.getSomeObjectList();
}
void run(){
//somobjLst used in a loop here, no additong are done it , but its value is used
}
}
- Now if at some point of time if some objects are added to
Cache.someObjectList
will it reflect in class A. I think 开发者_开发知识库it should as A only holds a refrence to it. - Will there will be any problem in A's code when content of
Cache.someObjectList
change?
EDIT: As per suggestions : if i make
void run (){
while(true){
synchronized(someObjList){
}
try{
Thread.sleep(INTERVAL);
}catch(Exception e){
}
}
}
will this solve problem?Yes, the changes will be reflected in class
A
as well. Exactly as you say:A
holds a reference to the exact same object asCache
.Yes, it can lead to a problem if
A
doesn't expect it to change. It also can lead to a problem if theList
implementation is not thread safe (most general-purpose implementations are not thread-safe!). Accessing a non-thread-safe data structure from two threads at the same time can lead to very nasty problems.
Sure, you are holding reference to collection in your thread. If collection is changed while you are iterating over it in thread ConcurrentModificationException
will be thrown.
To avoid it you have to use some kind of synchronization mechanism. For example synchronize the iteration over collection and its modification done in other thread using synchronize(collection)
.
This is a kind of "pessimistic" locking.
Other possibility is to use collections from java.util.concurrent
package.
精彩评论