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?
If you are implementing a
Queuewhich may need to throw anInterruptedExceptionthen 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 aBlockingQueuethe normalQueueoperations will either succeed or fail immediately. TheQueueinterface provides for throwing anIllegalStateExceptionif theaddmethod can not succeed or returningfalseif theoffermethod fails. New methodsputandtakeas well as an overloaded variant ofofferandpollare introduced by theBlockingQueueinterface for operations that may block and therefor need to throw anInterruptedException.