[concurrency-interest] concurrency puzzle

Jeremy Manson jmanson at cs.umd.edu
Tue Sep 12 14:27:20 EDT 2006

If foo() is executed in one thread, and bar() is executed in another, 
then your explanation is the right one, and this program can print 20 or 10.

About your second question -- "this program can print 20 or 10" is the 
right explanation, no matter what happened in the runtime.  This is 
because there is no way, in this example, to tell if bar is executed 
before the assignment to a in foo().

If you restructure your example so you can tell that bar() is executed 
first, then the answer to that question might change.


Peter Veentjer wrote:
> I know 10 could be printed if the bar method is executed just after
> a=20 and just before the synchronized(this){println(a)}. But what if
> bar is executed some time before the foo method is called? Could 10
> still be printed?
> On 9/12/06, Peter Veentjer <alarmnummer at gmail.com> wrote:
>> I'm stilling thinking about the subject and I trying to think in the
>> happens before terms.
>> Another example with a happens before relation
>> private int a;
>> public void foo(){
>>     a = 20;
>>     synchronized(this){
>>         System.out.println(a);
>>     }
>> }
>> public void bar(){
>>     synchronized(this){
>>         a=10;
>>     }
>> }
>> In this example, could it happen that 10 is printed?
>> There is a happens before relation between x=10 and System.out.println
>> (when the lock is released at the end of the bar method, and acquired
>> in the foo method.

More information about the Concurrency-interest mailing list