yangty89
yangty89

Reputation: 97

Java AbstractQueuedSynchronizer and the template method pattern

While reading the source code of ReentrantLock, I found that internally it use a synchronizer which extends AbstractQueuedSynchronizer to control the lock. Doug Lea mentioned in this paper that AbstractQueuedSynchronizer serves as a "template method pattern", which helps simplify the coding of sub-classes.

However, Joshua Bloch advised in Effective Java that we should "favor composition over inheritance", because "unlike method invocation, inheritance violates encapsulation". And in my understanding, the "templates" in Spring (e.g. RedisTemplate, TransactionTemplate, etc.) follow this rule.

So, back to the AbstractQueuedSynchronizer and the synchronizer defined in ReentrantLock, I would like to know if its design (based on template method pattern) has any disadvantages. Many thanks!

Upvotes: 0

Views: 145

Answers (1)

user16269459
user16269459

Reputation: 11

In case of AbstractQueuedSynchronizer there are no disadvantages, because AbstractQueuedSynchronizer is carefully written in such a way that inheritance doesn't violate encapsulation:

  • there are no visible fields for child classes
  • all methods (except 5 protected ones) are final, so child classes cannot change them
  • child classes are allowed to override only 5 protected methods: tryAcquire(), tryRelease(), tryAcquireShared(), tryReleaseShared() and isHeldExclusively()

Effectively this implementation is equivalent to composition: just move the 5 overridable methods to a dedicated interface.

Upvotes: 1

Related Questions