mardi 25 août 2015

Is this Hashset usage thread safe?

I have a static HashMap which will cache objects identifed by unique integers; it will be accessed from multiple threads. I will have multiple instances of the type HashmapUser running in different threads, each of which will want to utilize the same HashMap (which is why it's static).

Generally, the HashmapUsers will be retrieving from the HashMap. Though if it is empty, it needs to be populated from a Database. Also, in some cases the HashMap will be cleared because it needs the data has change and it needs to be repopulated.

So, I just make all interactions with the Map syncrhonized. But I'm not positive that this is safe, smart, or that it works for a static variable.

Is the below implementation of this thread safe? Any suggestions to simplify or otherwise improve it?

public class HashmapUser {

  private static HashMap<Integer, AType> theMap = new HashSet<>();

  public HashmapUser() {
    //....
  }

  public void performTask(boolean needsRefresh, Integer id) {
    //....

    AType x = getAtype(needsRefresh, id);

    //....
  }

  private synchronized AType getAtype(boolean needsRefresh, Integer id) {
    if (needsRefresh) {
      theMap.clear();
    }

    if (theMap.size() == 0) {
      // populate the set
    }

    return theMap.get(id);
  }
}



from Newest questions tagged java - Stack Overflow http://ift.tt/1fE8MPF
via IFTTT

Aucun commentaire:

Enregistrer un commentaire