Avoid synchronized(this) in Java?

后端 未结 22 1437
予麋鹿
予麋鹿 2020-11-22 01:23

Whenever a question pops up on SO about Java synchronization, some people are very eager to point out that synchronized(this) should be avoided. Instead, they c

22条回答
  •  余生分开走
    2020-11-22 01:54

    A good example for use synchronized(this).

    // add listener
    public final synchronized void addListener(IListener l) {listeners.add(l);}
    // remove listener
    public final synchronized void removeListener(IListener l) {listeners.remove(l);}
    // routine that raise events
    public void run() {
       // some code here...
       Set ls;
       synchronized(this) {
          ls = listeners.clone();
       }
       for (IListener l : ls) { l.processEvent(event); }
       // some code here...
    }
    

    As you can see here, we use synchronize on this to easy cooperate of lengthly (possibly infinite loop of run method) with some synchronized methods there.

    Of course it can be very easily rewritten with using synchronized on private field. But sometimes, when we already have some design with synchronized methods (i.e. legacy class, we derive from, synchronized(this) can be the only solution).

提交回复
热议问题