Reputation: 41
Using a variable we can ensure that only one method execution is in progress at any time, please see below the proposed code. I am wondering why do we use synchronized then?
public class Test {
private static boolean lock = false;
public void testMethod() {
if(lock){
System.out.println("Method run is in progress");
return;
}
lock=true;
try{
System.out.println("Doing some stuffs here");
}
catch(Exception e){
}
finally{
lock=false;
}
return;
}
}
Upvotes: 0
Views: 40
Reputation: 23349
Things that synchronized
offers that your "lock" doesn't
reentrant
, threads holding the lock can re-enter the critical section.lock
in a multi-threaded env. Do some research on race-conditions
and memory-barriers
Upvotes: 1
Reputation: 234875
It's not that simple.
A simple counter-example to your scheme: if two threads encounter your function testMethod
at the same time, then both could see lock
as being false
.
The same applies to the code in your finally
block.
Upvotes: 2