Link to home
Start Free TrialLog in
Avatar of Squadless
Squadless

asked on

synchronization java hashmap

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

Avatar of CPColin
CPColin
Flag of United States of America image

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.
Avatar of Squadless
Squadless

ASKER

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?
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial