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
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
}
}
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.
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.