1 LinkedBlockingQueue queJobs = new LinkedBlockingQueue(150); 2 .......... 3 .. Some other code.... 4 .......... 5 Job curJob = queJobs.take(); 6 .................... 7 .. Again some other code... 8 .................... 9 if(condition1){ 10 queJobs.put(curJob); 11 }
my problem is when condition1 is true, I am putting back the object into queu开发者_Go百科e. but initially it was on top of the queue, but after putting, it will go at the end of queue.
My requirement is : 1. I can put back the element on top of the queue or 2. Somehow I can wait at line 5, without removing element from the queue.A Queue is defined to be read at one end and written to at the other end. So no, can't put it back in. But you can use a LinkedBlockingDeque instead, which is more versatile in this regard.
If this is not an option, you can use peek() to get, but not remove, the curJob
and later only remove it if (!condition1)
.
UPDATE
but I am using take() because, it blocks the execution until queue is empty.
peek() will certainly not work for you then. But I suspect a shortcoming in your overall logic then. Normally you shouldn't have to put jobs back in the queue. Maybe the better solution is to use another collection which is only known to the worker thread, where you put the jobs that you started but not yet finished, and you read from that collection before the job queue.
You can use peek() which retrieves the head but does not remove it. Then later check whether condition1 is false. If yes, then remove it with take().
It is possible to add the element back to the head but it is messy. You can call toArray().toList() which supports adding at index 0.
Reference: http://download.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html
A more natural fit might be to use a PriorityBlockingQueue that would allow you to assign priorities to the elements. This is not exactly what you asked for, but is just a suggestion.
精彩评论