[concurrency-interest] Ordered puts and takes

Jim Andreou jim.andreou at gmail.com
Mon May 11 12:26:46 EDT 2009


Wow, sorry about that. I somehow didn't see the earlier replies.

2009/5/11 Jim Andreou <jim.andreou at gmail.com>:
> 2009/5/11 Alex Miller <alexdmiller at yahoo.com>:
>>
>> This is maybe a better question for the jmm list, but I'll start here and you can tell me to stuff it if so.
>>
>> If you have 2 unbounded LBQs:
>>
>>  LinkedBlockingQueue queueA = new LinkedBlockingQueue();
>>  LinkedBlockingQueue queueB = new LinkedBlockingQueue();
>>
>> and 1 producer thread puts objects on queue A then queue B (no other synchronization):
>>
>>  queueA.put(obj1);
>>  queueB.put(obj2);
>>
>> and you have a consumer that reads those queues (no other synchronization):
>>
>>  Object seen1 = queueA.take();
>>  Object seen2 = queueB.remove();
>>
>> Is
>> it possible to see NoSuchElementException from the final remove()?  I
>> think this boils down to a JMM question of whether the puts
>> (which are changing the queues on separate internal locks but are
>> sequentially ordered in the producer thread) *guarantee* an ordering in the consumer thread such that obj1 must show up on queueA before obj2 on
>> queueB.
>
> I don't see a guarantee that the consumer will observe the program
> order of the producer. The two puts can be reordered if this
> reordering can't be observed in the producer thread, so the consumer
> may see the "wrong" order.
>
> Also, think that the producer could be preempted before putting to the
> second queue.
>
> I think that if you reordered the consumer like this:
>
> Object seen2 = queueB.take();
> Object seen1 = queueA.remove();
>
> Then you would have the intented ordering. If you see the second
> object, then the put on the queueB happened-before, and the put on
> queueA happened-before that because it was earlier in program order.
>
>>
>> My intuitive answer is yes but the actual answer might be that this is merely likely, not guaranteed.
>>
>> Thanks...
>> Alex
>> _______________________________________________
>> Concurrency-interest mailing list
>> Concurrency-interest at cs.oswego.edu
>> http://cs.oswego.edu/mailman/listinfo/concurrency-interest
>>
>



More information about the Concurrency-interest mailing list