What's the difference between Synchronized and Lock in my example?

前端 未结 2 931
我寻月下人不归
我寻月下人不归 2020-12-09 14:05

I wrote a simple code to mock concurrency using Lock and synchronized.

Source code is as follows:

Task class inclu

相关标签:
2条回答
  • 2020-12-09 14:52

    First of all, your example using synchronized is ill conceived: it is a very bad idea to synchronize on object "A". Use the following idiom instead:

    private final Object lock = new Object();
    
    public void run() {
        synchronized (lock) {
            doSomething();
        }
    }
    

    This is better because by hiding your lock from external objects, you are encapsulating your synchronization protocol and thereby implementing a safer synchronization policy.

    Now, the difference between synchronized and java.util.concurrent.locks.Lock, is that the former is a synchronization primitive whereas the latter a higher level locking construct which provides more elaborate operations than synchornized.

    Fore more information you may look at http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/Lock.html and http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html in particular.

    0 讨论(0)
  • 2020-12-09 15:02
    synchronized ("A")
    

    it's not a proper usage of synchronized block. you create a different String object (in some cases) when entering this sync block, so each your thread have a different lock object and do not synchronize. Proper usage may be like

    synchronized(this)
    

    or

    public class TaskWithSync extends Task implements Runnable {
        private Object lock = new Object();
    
        @Override
        public void run() {
    
            synchronized (lock) {
                doSomething();
            }
        }
    }
    

    In addition, you should use a single Runnable implemenation in different threads, or make your lock a static field

    0 讨论(0)
提交回复
热议问题