Why can't an abstract method be synchronized?

前端 未结 4 1047
深忆病人
深忆病人 2020-12-13 00:45

I was reading a thread from CodeRanch saying that abstract methods could not be synchronized due to the fact that an abstract class cannot be instantiated, meaning no object

4条回答
  •  盖世英雄少女心
    2020-12-13 01:38

    Locking behavior shouldn't be specified using abstract methods or interface methods because it shouldn't be part of the contract.

    Probably the idea was that locking behavior is fundamentally part of the implementation -- different implementations will want to perform locking differently -- and it would be counterproductive to specify it at that level of abstraction.

    Remember the keyword synchronized is specifically for implementing implicit locking (acquiring the lock on the object that the instance method is called on), and there are ways to do locking using alternatives like ReentrantLock, where that keyword is not applicable, or possibly to use CAS or otherwise avoid locking altogether.

提交回复
热议问题