Avoid synchronized(this) in Java?

后端 未结 22 1196
予麋鹿
予麋鹿 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:48

    This is really just supplementary to the other answers, but if your main objection to using private objects for locking is that it clutters your class with fields that are not related to the business logic then Project Lombok has @Synchronized to generate the boilerplate at compile-time:

    @Synchronized
    public int foo() {
        return 0;
    }
    

    compiles to

    private final Object $lock = new Object[0];
    
    public int foo() {
        synchronized($lock) {
            return 0;
        }
    }
    

提交回复
热议问题