开发者

Using variable reference to point to static member of some other class

开发者 https://www.devze.com 2023-03-24 21:57 出处:网络
I have a class Cache which picks up List<SomeObject> someObjectList from DB and stores it in static variable.

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
 }
}
  1. 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.
  2. 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?


  1. Yes, the changes will be reflected in class A as well. Exactly as you say: A holds a reference to the exact same object as Cache.

  2. Yes, it can lead to a problem if A doesn't expect it to change. It also can lead to a problem if the List 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消