Synchronization on object, java

This question already has an answer here:

  • Avoid synchronized(this) in Java? 18 answers

  • First some basics:

    The synchronization object is used as a key to open a door to a restricted area (the synchronization block).

    As long as a thread entered this restricted area it holds the monitor (lock) so that no other thread can enter. When a thread exits the restricted area it releases the monitor and another thread can take it.

    This means that each synchronization block that uses the same synchronization object will prevent other thread to enter until the monitor is available (unlocked).

    For what reason does the creation of new dummy object serve?

    The reason is that you should use objects that are not accessible by others objects than the ones that use them. That's why the synchronization objects are private . If they would be accessible by others, other might use them in their synchronization blocks somewhere in the application. If the synchronizcation object is eg public then every other object can use it. This might lead to unexpected usage and might result in deadlocks.

    So you should make sure who will get a reference to the synchronization object.


    The lock is accessed by the threads to check if the code is currently "in use" or if they can execute it after locking the object themselves. You may think it could be automatic, but it has a use compilers couldn't infer : you can use the same lock to synchronize multiple code blocks, restraining the access to any of them at the same time.


    In my opinion, dummy Object just represents the point of synchronization.

    For synchronize different threads, you must be able to declare point of synchronization and(if it is needed) give access to this point from different parts of the code. For example:

       private Object lock = new Object();
    
       public void inc1() {
              synchronized(lock) {
                   c1++;
              }
       }
    
       public void inc2() {
              synchronized(lock) {
                   c2++;
              } 
       }
    

    In this example shown the usage of same point of synchronization from different part of code.

    And because Java is Object oriented language ie unit of language in Java is Object, we have exactly such a construction.

    By the way, you can use any object in as point of synchronization. You can do even this:

    public void inc1() {
           synchronized(this) {
                c1++;
           }
    }
    
    链接地址: http://www.djcxy.com/p/76260.html

    上一篇: 在Java中同步其他对象

    下一篇: 同步对象,java