Re: Java multi-threading question: 'Serial Concurrency'
On 12.04.2008 12:12, Messi wrote:
I have a question regarding Java concurrency: Usually, when multiple
threads are involved, we have to synchronize (meaning both
'synchronized' and 'java.util.concurrent' thread-synchronization) them,
on the one hand for 'real' contention (two threads really concurrently
accessing an object) and even for 'pseudo' contention (where, in
reality, threads are accessing an object one after the other) due to the
Java memory-model.
There is no thing as pseudo contention. As long as at least two threads
execute concurrently and potentially access the same resource you need
to synchronize one way or another.
My question is: What if some code is 'purely single threaded' (i.e two
threads will never run through it concurrently) but is executed serially
by different threads?
That would be called "thread confinement", i.e. the resource is confined
to a single thread at a point in time.
If, without synchronization, one thread may not
see what another has done, it will still need to be synchronized, but if
so, this means more or less everything executed via an 'Executor' has to
be synced... but that doesn't seem to be the case, so is it ok to
execute unsynchronized code serially by different threa?
Yes, of course.
If so, how does
that work (if, without sync, threads may not see modifications done by
others, how do they in this case?).
There will be a memory barrier if the second thread is created (your
case). If the second thread lives earlier but learns of the resource
after the first thread exited or completed its work on the resource
there will be a memory barrier as well - usually data is communicated
via some synchronized queue in typical farmer worker implementations or
light weight execution frameworks.
There is a very good book available on this written by Doug Lea who also
authored concurrency utilities for Java 5.
Kind regards
robert