How do I synchronize this properly?

97 Views Asked by At
public void consumeResponse(OmwListResponse<T> response) {
    synchronized (response.getResultList()) { // XXX this isn't synchronized safely
        for (T t : response.getResultList()) {
            if (!cacheList.contains(t)) {
                cacheList.add(t);
            }
        }
    }
}

The the situation is I don't want anyone to chance response.getResultList() or cacheList until this method is done. How do I properly do this?

2

There are 2 best solutions below

7
On BEST ANSWER

Create a lock object:

private static final void LOCK = new Object();

and synchronize on that.

0
On

Synchronizing cacheList is easy. Just wrap any code your code that uses it in:

synchronized(cacheList) {
   // Make changes to cacheList here
}

If cacheList is a public member and you're afraid external classes will change it, make it a private member and synchronize the getter and setter. This is the only way since you have no control over what other classes do and it is your responsibility to synchronize your members.

As for response, that is trickier because I don't what an OmwListResponse is. Do you own that class? If so, use the same method as above. If not, you may be out of luck.