简体   繁体   中英

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 synchronized only 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 Lock can be a replacement for synchronized .

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

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();
    }
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM