views:

287

answers:

1

Java's Executor is (as far as I understand it) an abstraction over the ThreadPool concept - something that can accept and carry out (execute) tasks.

I'm looking for a similar exception for the Polling concept. I need to continuously poll (dequeue) items out of a specific Queue (which does not implement BlockingQueue), execute them and sleep, and repeat all this until shutdown.

Is there a ready-made abstraction or should I write something on my own?

(Suggestions of a better title are welcome)

+2  A: 

Polling is easy:

Thread t = new Thread(new Runnable() {
    public void run() {
        try {
            while (!t.isInterrupted()) {
               Object item;
               while ((item = queue.take()) == null) {//does not block
                   synchronized (lock) { lock.wait(1000L) } //spin on a lock
               }
               //item is not null
               handle(item);
            }
        } catch (InterruptedException e) { }
    }
});
t.start();

Perhaps you need to rephrase your question as I'm not quite sure exactly what it is you are trying to do?

oxbow_lakes
My own queue is something custom (a GigaSpaces queue), it does not implement the BlockingQueue interface.
ripper234
Then add a simple adapter which does implement the interface and delegates to your queue impl
oxbow_lakes
I can't - GigaSpaces is a distributed grid - the push() operations to the queue are done on another computer. Ergo, what I need is actual polling - I don't see how I can implement BlockingQueue.
ripper234
The queue's interface is write() and take() - and since the write() is happening on another computer (and my process might not even be up at that point), there's no operation I can take then.What I need is a thread that keeps polling this queue (calling take()), with some minimal lifecycle management.
ripper234
Does take() not block? (See my answer above). I still don't see why you can't write an adapter (it doesn't matter who is putting items on the queue as long as the take operation behaves as it should)
oxbow_lakes
take() unfortunately doesn't block.
ripper234
Correction - take() can block for a specific amount of time, but I guess my actual situation is more complicated than I described here - I'd like to takeMultiple(), and more...I guess your answer answers my question as phrased.
ripper234
See my modified answer - the polling is really easy and there's no need of a control abstraction. Please ignore the Quartz answer; Quartz has nothing whatsoever to do with your problem
oxbow_lakes
How about an upvote then :-)?
oxbow_lakes
ripper234