Sabir Khan
Sabir Khan

Reputation: 10142

can synchronized at method level be replaced by Lock?

When writing a thread safe class, we use synchronized keyword at two places in code,

1.Method level synchronization

2.Synchronized blocks

As far as I can think of, interfaces like Lock (java.util.concurrent.locks.Lock)can be used in place of synchronizedonly at block level but not at method level. or is there a way?

I don't have any real need of it but just curios since heard discussions that Lockcan be a replacement for synchronized.

public class SampleClass {
    public synchronized void method(){
      .....
    }
}

Upvotes: 1

Views: 589

Answers (3)

beatngu13
beatngu13

Reputation: 9423

No, there's no way to do this since java.util.concurrent—and therefore Lock or any other implementation as well—is just a library, whereas synchronized is part of the Java Language Specification.

Regarding "Lock can be a replacement for synchronized", Brian Goetz discusses this in "Java Concurrency in Practice" in chapter 13.4:

ReentrantLock is an advanced tool for situations where intrinsic locking is not practical. Use it if you need its advanced features: timed, polled, or interruptible lock acquisition, fair queueing, or non-block-structured locking. Otherwise, prefer synchronized.

Upvotes: 1

talex
talex

Reputation: 20544

As we all know

public class SampleClass {
    public synchronized void method(){
      .....
    }
}

and

public class SampleClass {
    public void method(){
        synchronized(this) {
           .....
        }
    }
}

is equivalent for all practical purposes.

So you need to change method synchronization to equivalent block synchronization and the later can be replaced by Lock

Upvotes: 1

yshavit
yshavit

Reputation: 43401

There is no special syntax for "acquire the Lock at the beginning of the method, and release it at the end," like there is for synchronized.

You can, of course, just do that yourself:

public void method() {
    lock.lock();
    try {
        // rest of the method
    } finally {
        lock.unlock();
    }
}

Upvotes: 4

Related Questions