While learning Java concurrency I ran into this behaviour which I can't explain:
public class ThreadInterferrence implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread t = new Thread(new ThreadInterferrence());
t.start();
append("1", 50);
t.join();
System.out.println(value);
}
private static String value = "";
public void run() {
append("2", 50);
}
private static void append(String what, int times) {
for (int i = 0; i < times; ++i) {
value = value + what;
}
}
}
Why does the program generate random Strings? More importantly why does the length of output vary? shouldn't it always be exactly 100 chars?
Output examples:
22222222222222222222222222222222222222222222222222
1111111111111111111111111111112121112211221111122222222222222
etc..
On the topic of your updated question (why does the length of output vary? shouldn't it always be exactly 100 chars?)
The behavior will be unpredictable, since the re-assignment of the new String is not atomic. Note that Strings are immutable and you keep reassinging a value to a variable. So what is happening is one thread gets the value, the other thread also gets the value, one thread adds a character and writes it again but so does the other thread with the old value. Now you're losing data because the update from one of the threads is lost.
In such a case you could use a StringBuffer which is thread-safe, or add synchronization which I'm sure you'll learn about.