Reputation: 10841
I am writing a custom queue implementing the queue interface. This implementation is thread safe and blocks on certain occasions.
The normal Queue interface does not mention Exceptions, therefore I can't throw any InterruptedException
in my implementation.
I see two solutions for this problem, but they are both not very satisfying:
Remove the Queue interface and throw Exceptions. This makes the code unusable for foreign software that requires a Queue.
Throw RuntimeException
, this will yield tonnes of very surprising software activity, which I don't want to risk.
Somehow implementations like ArrayBlockingQueue
manage to implement Queue
and BlockingQueue
. Is that the way to go, or what is the trick here?
Upvotes: 1
Views: 135
Reputation: 20442
If you are implementing a Queue
which may need to throw an InterruptedException
then my guess is that you really want to implement a BlockingQueue. If you read the javadoc for this interface, you will realize that the Java language designers have basically said that in the context of a BlockingQueue
the normal Queue
operations will either succeed or fail immediately. The Queue
interface provides for throwing an IllegalStateException
if the add
method can not succeed or returning false
if the offer
method fails. New methods put
and take
as well as an overloaded variant of offer
and poll
are introduced by the BlockingQueue
interface for operations that may block and therefor need to throw an InterruptedException
.
Upvotes: 2
Reputation: 1409
You should go with option one.
When people want to have a Queue (interface) on their hand they will expect the queue to work a certain way. The behavior is specified in the interface and the client do not need to worry about the implementation or make changes when they switch.
This is not the case with your queue, if you implement this interface but throws run-time exception you will be breaking the expectation of your client in an unexpected manner. The foreign software asks for a Queue precisely because they don't want to be "tricked" to get something non-interchangeable.
Better to make this explicit by not implementing Queue, unless you can handle the interrupted exception transparently within your object.
Upvotes: 1