Say I have an Object Foo that wants to get informed by several running instances of a Thread using a listener interface. E.g.
The interface:
public interface ThreadListener {
public void onNewData(String blabla);
}
The class Foo:
public class Foo implements ThreadListener {
public Foo() {
FooThread th1 = new FooThread();
FooThread th2 = new FooThread();
...
th1.addListener(this);
th2.addListener(this);
...
th1.start();
th2.start();
...
}
@Override
public void onNewData(String blabla) {
...
}
}
The Thread:
public FooThread extends Thread {
private ThreadListener listener = null;
public void addListener(ThreadListener listener) {
this.listener = listener;
}
private void informListener() {
if (listener != null) {
listener.onNewData("Hello from " + this.getName());
}
}
@Override
public void run() {
super.run();
while(true) {
informListener();
}
}
}
In the worst case onNewData(..) is invoked by several threads at the same time. What will happen with Foo? Is it going to crash or not?
Fooclass has no state (fields), so unless it uses external shared resources (e.g. files…) it is thread safeonNewDatadoes not access shared data it will work as expected, if it does, the outcome will depend on how the method is implemented.