It's not a secret anymore!
The moose likes Threads and Synchronization and the fly likes Question about BlockingQueue Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Threads and Synchronization
Reply Bookmark "Question about BlockingQueue" Watch "Question about BlockingQueue" New topic
Author

Question about BlockingQueue

Peter Curila
Greenhorn

Joined: Oct 11, 2005
Posts: 20
Could somebody explain me why the "take" message is first and then is "put" when I run the test method test100().
It works but the messages confuse me.

I have class NumberQueue which is simple LinkedBlockingQueue for Integers with some messages after/before put and take.
Then I have test case class NumberQueueTest where I have defined two nested classes Filler and Taker. Filler takes array of int
and put them into the queue and Taker takes them from the queue. Boths classes extends Thread of course. In test test100 i create 2Fillers and 2Takers.
Its just test so it does not do anything meaningful.

Here is the output

Queue constructed
taker 0 before take:
taker 1 before take:
filler 0 before put: 1
taker 0 after take: 1 // here I took 1
taker 0 before take:
filler 0 after put: 1 // and here I put 1
filler 0 before put: 2
taker 1 after take: 2
taker 1 before take:
filler 0 after put: 2
filler 1 before put: 3
taker 0 after take: 3
filler 1 after put: 3
filler 1 before put: 4
taker 1 after take: 4
filler 1 after put: 4

and here is the code:

Joe Ess
Bartender

Joined: Oct 29, 2001
Posts: 8290

Your put() and take() methods are not synchronized so they do not perform their actions atomically (i.e. without interruption). I haven't looked at BlockingQueue, but when you "put" something onto the BlockingQueue, it probably invokes notify() or notifyAll() to wake threads waiting on get() invocations. The thread that invoked take() gets the CPU at that point and you see the print outs from that execution.


"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Question about BlockingQueue
 
Similar Threads
Producer Consumer Controller
multithreading not working correctly
currentthread().getName() not returning name
Thread causing Hang ??