The Sun Java (1.6) ScheduledThreadPoolExecutor
which is an extension of ThreadPoolExecutor
internally uses an implementation of DelayQueue
which is an unbounded queue. What I need is a ScheduledThreadpoolExecutor
with a bounded queue i.e. it has a limit on the tasks accumulating in the queue so that when tasks in queue exceed the limit, it starts rejecting the further submitted tasks and prevents JVM going out of memory.
Surprisingly, google or stackoverflow did not point me to any results which are discussing this problem. Is there any such thing already available I am missing out? If not, how can I implement a ScheduledThreadpoolExecutor to provide me my expected functionality in a best way?
As others have already pointed out, there isn't a ready way of doing this. Just make sure you try to use "composition" instead of "inheritance". Create a new class which implements the necessary interface and delegate to the underlying ScheduledThreadPoolExecutor
by doing checks as per required on the necessary methods.
You can also use the technique specified in this thread with a simple modification. Instead of using Semaphore#acquire
, you can use Semaphore#tryAcquire
and depending on the boolean outcome decide whether you need to call the rejection handler or not. Come to think of it, I personally feel that it was an oversight on the part of the library authors to directly subclass a specific executor rather than relying on composition to create a "schedulable" wrapper over a normal executor.
How about handling it differently i.e. depending upon the queue size delay the task subsmission. The executor services exposes the queue via getQueue(). You can invoke the size() on it and depending upon the limit you plan for the queue size, you can either start rejecting the tasks or start delaying the task execution (increase the scheduled time keeping the size of the queue as one of the factor).
All said, this is again not the best solution; just fyi, java provides delay queue to support work stealing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With