I am new to Java multithreading. Since I need a thread-safe singleton (which I implemented as an enumeration), I wrote a little test code that produces strange output.
Code:
public enum EnumSingleton {
INSTANCE;
private String message;
private EnumSingleton() {
}
public static EnumSingleton getInstance() {
return INSTANCE;
}
public String getMessage() {
return message;
}
public void setMessage(String name) {
this.message = name;
}
}
public class App {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
final int b = i;
Thread thread = new Thread("Thread #" + b) {
@Override
public void run() {
EnumSingleton singleton = EnumSingleton.getInstance();
singleton.setMessage("Message written by "+this.getName());
System.out.println("Current thread "+this.getName() + ": "+singleton.getMessage());
}
};
thread.start();
}
}
}
Thus, each thread writes its name to the enumeration "message" property, which is then printed in STDOUT. I get the following output, which I find strange:
Current thread Thread #6: Message written by Thread #3
Current thread Thread #1: Message written by Thread #1
Current thread Thread #8: Message written by Thread #8
Current thread Thread #5: Message written by Thread #1
Current thread Thread #4: Message written by Thread #4
Current thread Thread #9: Message written by Thread #9
Current thread Thread #7: Message written by Thread #3
Current thread Thread #2: Message written by Thread #3
Current thread Thread #0: Message written by Thread #3
Current thread Thread #3: Message written by Thread #3
I expected that I get a message for each loop counter (0-9). But in this example, I have several posts written by Thread # 3, how can this be? Is there a racial condition?
If my code is crappy: how to check my singleton for thread safety?