Reputation: 503
I would an explanation on these different implmentations:
First:
public void foo(Object key){
synchronized (map.get(key)) { //-> thread can enter with different key
int variable = 0;
for (int j = 0; j <new Random().nextInt(10); j++)
variable+=j;
return variable;
}
}
Second:
public void foo(Object key){
int variable = 0;
synchronized (map.get(key)) {
for (int j = 0; j < new Random().nextInt(10); j++)
variable+=j;
return variable;
}
}
Third:
public void foo(Object key){
int variable = 0;
synchronized (map.get(key)) {
for (int j = 0; j <new Random().nextInt(10); j++)
variable+=j;
lock.lock(); // class instance lock
try{
setTheVariable(variable) //-> Example.....
}finally{
lock.unlock();
}
return variable;
}
}
In my opinion the first two implementations are the same, if each thread enter the syncrhonized
block
they share the for loop
but they have got their own variable
copy, is right?
I have a doubt in the third implementation, if each thread enter the syncrhonzized block
, after finishing only one can enter inside the lock block
and the other have to wait. In this case when one thread can return each variable resulting of the for loop
remains attached on his own thread
?
thanks in advance.
Upvotes: 0
Views: 62
Reputation: 118
Variables declared inside the foo() method remains attached to the individual threads,because they are local variables. Here you are declaring "j" and "variable" inside the method and those variables will remain attached to the thread executing the method.
Upvotes: 1
Reputation: 903
Your first two implementations are the same.
In your third implementation, only one thread can enter the synchronized block, irrespective of whether it is an class instance variable, so the lock
is somehow redundant unless your //Do Something Here
section has a compelling reason to do so.
Because all the variables involved are local variables, each thread has its own copy of these variables. The returned value of one thread will not be affected by another thread.
However, always watch out for deadlock if two locks are used in this fashion.
Upvotes: 1