Java multi-threading question: 'Serial Concurrency'
Hi all,
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.
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? 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? If so, how does
that work (if, without sync, threads may not see modifications done by
others, how do they in this case?).
For illustration of the point, I've written the code at the end, where
the 'wrongSync' method clearly has concurrency problems (undefined
behavior), but what about 'maybeWrongSync'?
Would be very glad for an answer or a pointer to explaining resources
(without needing to wholly understand the JMM/JVM ;-) ).
kind regards,
Messi
CODE:
package com.syd.test.toc;
import java.util.ArrayList;
import java.util.List;
/**Illustrating code*/
public class SerialConcurrency {
/**What about this? threads run serially through {@link
ConcurrencyTest#run()}, but what about "unsynchronized, a thread may not
see what another thread has done"???*/
private static void maybeWrongSync() throws Exception {
ConcurrencyTest ct=new ConcurrencyTest();
for(int i=0; i<10; i++) {
Thread t=new Thread(ct);
t.start();
t.join();
}
}
/**Wrongly synchronized: multiple threads run through {@link
ConcurrencyTest#run()} method and modify an unsynced list concurrently*/
private static void wrongSync() {
Thread[] threads=new Thread[10];
ConcurrencyTest ct=new ConcurrencyTest();
for(int i=0; i<threads.length; i++) {
threads[i]=new Thread(ct);
}
for(int i=0; i<threads.length; i++) {
threads[i].start();
}
}
private static class ConcurrencyTest implements Runnable {
private List list=new ArrayList();
public void run() {
try {
for(int i=0; i<5; i++) {
list.add(new Object());
Thread.sleep(100);
}
}
catch(InterruptedException iex) {
System.out.println("iex caught: "+iex);
}
}
}
}