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.someObjectListwill 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.someObjectListchange?
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
Aas well. Exactly as you say:Aholds a reference to the exact same object asCache.Yes, it can lead to a problem if
Adoesn’t expect it to change. It also can lead to a problem if theListimplementation 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.