>> Hi, I was asked this in an interview. Given the following, how would I
>> make the below code "thread safe"?
[quoted text clipped - 11 lines]
> The answers you have already been given are good as far as this code is
> concerned.

Signature
Steve Wampler -- swampler@noao.edu
The gods that smiled on your birth are now laughing out loud.
>>> Hi, I was asked this in an interview. Given the following, how would I
>>> make the below code "thread safe"?
[quoted text clipped - 8 lines]
>>> public Foo getFoo() {
>>> return _foo; } }
...
> Out of idle curiousness, would someone mind explaining just what could go
> wrong with the above code (as written) when used in a threaded environment?
> I understand why the answers are good in general, but would like to
> understand what behavior they are preventing in this simple class.
Ah, to partially answer my own question: without volatile, an optimizer may
not realize that _foo can be changed in another thread and perform
an optimization that results in the 'external' value change being ignored - right?
Is that true of using synchronization as well? It prevents such optimizations?
(Or is there a separate issue that is addressed with the synchronization?)
Same questions about using an AtomicReference, of course.
Thanks!

Signature
Steve Wampler -- swampler@noao.edu
The gods that smiled on your birth are now laughing out loud.
Michael Rauscher - 27 Jul 2006 23:12 GMT
Hi Stefe,
to refine my answer:
Steve Wampler schrieb:
>> Out of idle curiousness, would someone mind explaining just what could go
>> wrong with the above code (as written) when used in a threaded environment?
[quoted text clipped - 4 lines]
> not realize that _foo can be changed in another thread and perform
> an optimization that results in the 'external' value change being ignored - right?
Yes. Without volatile each thread may hold the variable in a "private
working memory". A volatile field is "synchronized" with main memory on
each access.
> Is that true of using synchronization as well? It prevents such optimizations?
No, it doesn't prevent optimizations. In a synchronized method/block the
"synchronization" of the field with main memory is done when the lock is
obtained or released.
Bye
Michael
Steve Wampler - 28 Jul 2006 02:23 GMT
> Hi Stefe,
>
[quoted text clipped - 17 lines]
> "synchronization" of the field with main memory is done when the lock is
> obtained or released.
Thanks!! I was wondering how synchronization would help with the volatility
of _foo - now I see it might be more efficient if there was a *lot* more code
inside setFoo or getFoo that referenced _foo.
Thanks again.

Signature
Steve Wampler -- swampler@noao.edu
The gods that smiled on your birth are now laughing out loud.