synchronization java hashmap

Squadless
Squadless used Ask the Experts™
on
Hi,
My question is the following,  take a look at the code, one method is synchronized, the other is not.  The hashmap itself is not synchronized.  Is it possible for 2 threads to ever be here: ie: one thread is in the synchronized put block, and another thread is in the getItem method?

Why? Why Not?  Im pretty sure this is impossible for it to happen but i am not 100% sure.

Thanks
public class Test{
 private HashMap map = new HashMap();

public synchronized void putItem(Object x){
//put code
}

public Object getItem(Object x){
//get code
}
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
CPColinSenior Java Architect

Commented:
Since the getItem() method is not synchronized, there is nothing stopping it from executing at the same time as the putItem() method. So, yes, both methods could be running at once.

Author

Commented:
Ok but if thread 1 gets in the putItem method and locks on the hashmap, how can another thread lock on the same item in the getItem method?
Awarded 2011
Awarded 2011
Commented:
It looks like they can run simulatnaeously.
Still if you read what they write about non-synchromnization of HashMap in API it seems like some real
problems can occur if you don't make a special precaution if you modify structuraly HashMap, i.e.
when you create new key without synchronization. So you  don't need to synchronize get method.

This is from

http://download.oracle.com/javase/6/docs/api/java/util/HashMap.html :

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method.
CPColinSenior Java Architect
Commented:
Nothing in the getItem() method is instructing the Java VM to obtain a lock on anything. If the getItem() method were also synchronized, only one of the two methods would be allowed to run at any time.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial