synchronization and HashMaps

I have a HashMap called sCache. 2 or more threads may call put on this map.

public class A

{

public Object someMethod (StringBuffer buffer)

{

Object o = sCache.get(buffer.toString());

if (o == null) {

// Need to create value for this key and cache it

// createValue method is just for illustration purposes

o = createValue(buffer);

sCache.put(buffer.toString(), o);

}

return o;

}

private static Map sCache = new HashMap();

}

My question is about threading and the memory model. If i have no sychronization around this sCache when does one thread see another's put?

My understanding is that each thread could or would hold a local reference to this map so therefore for thread communication purposes we would only need to synchronize if the Map reference were originally null and one thread were instantiating the HashMap? That isn't the case here. Since the actual object referred to by the sCache reference never changes in this example, would i need to synchronize?

[1081 byte] By [bgika] at [2007-11-27 0:41:44]
# 1
One thing i should add is that the createValue method creates the same value for any thread and has a low overheadthanks
bgika at 2007-7-11 22:55:39 > top of Java-index,Core,Core APIs...
# 2

HashMap is not thread-safe so you need to do something to synchronize those concurrent put()s even if they are trying to put in the same value.

Use ConcurrentHashMap instead.

Also for general caching strategies google for the "Memoizer" pattern. It is described in "Java Concurrency in Practice" by Goetz et al and has been presented at JavaOne.

davidholmesa at 2007-7-11 22:55:39 > top of Java-index,Core,Core APIs...