A project requires the following scenario to happen:
class A
has some objects(dynamically created) which it generates along with a time interval
associated with each object. This class needs the generated object after this time interval
only. I need to implement a mechanism which provides the class with the objects after it's associated time interval
. It may also, sometime, need a particular object before the time interval
expires.
Here's what I did:
Looked upon ConcurrentTaskExecutor and org.springframework.scheduling.concurrent but didn't find it useful because I don't want thousands of thread running each for an object. Also, I don't want to repeat a particular job after a time interval.
I created a
Thread B
which takes all the object in a queue, has an infinite loop which constantly checks all the object'stime interval
with the current time, and puts back if it'stime interval
has not expired.while (true) { timerObject = queue.take(); if (timerObject.getEndTime() < System.currentTimeMillis()) { //Do something } else { queue.put(timerObject); } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } }
This is not a very efficient implementation itself. It has a logical error associated with it. When the objects are very low in number(like 1 or 2), the objects are not in the queue and whenever I try to remove the object from the queue, it shows unsuccessful
, because the while loop is having the object all the time. And hence I had to put a sleep
to avoid that. I don't want to check each and every time interval
when the queue size grows up to 10K or so.
Is there any simple and efficient way to achieve the solution. Any help appreciated.