meelo
meelo

Reputation: 41

Why using a synchronized keyword when we have a simpler way

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

Answers (2)

Sleiman Jneidi
Sleiman Jneidi

Reputation: 23349

Things that synchronized offers that your "lock" doesn't

  1. Synchronized is reentrant, threads holding the lock can re-enter the critical section.
  2. Synchronized provides fresh visibility for the mutex and the data in the section, yours will fail to get the actual value of lock in a multi-threaded env.

Do some research on race-conditions and memory-barriers

Upvotes: 1

Bathsheba
Bathsheba

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

Related Questions