peng
peng

Reputation: 1

why AbstractQueuedSynchronizer's subclass should be internal class?

My jdk version is 1.6,I find a description of AbstractQueuedSynchronizer like this:

Subclasses should be defined as non-public internal helper classes that are used to implement the synchronization properties of their enclosing class.

What are the benefits of using internal class?

Upvotes: 0

Views: 151

Answers (4)

peng
peng

Reputation: 1

Thank you all!Synthesize your answers,maybe the reasons of the question are:

  1. usually the subclass is just used by it's outer class,so there is no need to define a normal class in jdk

  2. we can use composition instead of extend。At the same time,we can avoid exposing those unwanted methods

thank you again!

Upvotes: 0

Alexander
Alexander

Reputation: 48262

It's because otherwise you will have to extend your own class from AbstractQueuedSynchronizer and you will not want to do that because it'll bring unnecessary dependency into your own class hierarchy.

Upvotes: 0

Holger
Holger

Reputation: 298183

AbstractQueuedSynchronizer provides lots of public methods and it is very unlikely that all of them make sense as part of your own public API. Exposing those unwanted methods can distract from the your actual API or even harm the stability of your code. Even worse, the API of this class could evolve, providing even more methods, you can’t know beforehand whether they are suitable for your use case.

Note that a lot of the concurrency tools of the java.util.concurrent package use this class internally, without exposing all of the AQS methods.

Also, using AbstractQueuedSynchronizer internally allows you to switch to another class, e.g. Java 6 introduced AbstractQueuedLongSynchronizer, while in Java 5 there was only AbstractQueuedSynchronizer, and some of the classes of the java.util.concurrent might have switched since then, without you noticing.

Upvotes: 1

Rajan Singh
Rajan Singh

Reputation: 324

AbstractQueuedSynchronizer is a framework that provides blocking mechanish for FIFO like structures. You can see many blocking structures extending this class's functionality to implement locking mechanism.

For example you can see ReentrantLock class providing fair/unfair locking through Sync class which extends AQS. Regarding internal classes, it's a case of Composition. The internal classes exist only exists to help their parent class.

I hope it helps.

Upvotes: 0

Related Questions