1 Reply Latest reply on Dec 20, 2012 1:38 PM by james_sutherland

    multithread issue:One thread updating value & other thread retrieving value

      I am using a spring bean (singleton) and this is how it looks like

      public class MySingletonService {

           private Map<String, List<TaskVO>> alerts = new HashMap<String, List<TaskVO>>();

      //spring will call this method every 15 minutes
           public void pollDatabase() {

      //initialize the alerts instance variable and create/fill the alerts instance variable with new alerts for the employee(from database) .The key for the hashmap is the employee id

      //some client code (e.g. GUI) will call this method to get the alert for the operator id.This can be called anytime to get the latest info from the alert Map      
           public List<TaskAlertVO> getOutstandingAlerts(String operatorId) {
                return alerts.get(operatorId);

      The issue here is that when getOutstandingAlerts is invoked by a thread,some other thread(Spring) calling the pollDatabase method might be updating the value.Please give me some idea and solution to get around this issue.
      I was thinking of creating a copy of alerts instance variable in the getOutstandingAlerts method and then use the copy to find the key and return the alert for that operator id.This way we dont have to worry about data conflict.

      Please advice

      Edited by: Manjit on Dec 12, 2012 1:55 PM
        • 1. Re: multithread issue:One thread updating value & other thread retrieving value
          You need to use some form of synchronization or locking.

          You could make the getOutstandingAlerts() method and the method that updates the alerts synchronized.

          You could also switch to using a ConcurrentHashMap, and ensure you have fully built the new Task before adding it.

          Are you creating a new Task or changing an existing one? If you are changing an existing one you will need to synchronize around the whole usage of the task. You could instead create a clone.

          ...note sure what this has to do with TopLink though...