I saw the code below on the web, and it says "the code is not thread safe". I could not understand why? Since, each thread below runs the getList will not let any other one to reach to the getList()
.
public class MyClass {
private List<String> list;
public static void main (String[] args) throws InterruptedException {
MyClass obj = new MyClass();
Thread thread1 = new Thread(() -> {
System.out.println("thread1 : " + System.identityHashCode(obj.getList()));
});
Thread thread2 = new Thread(() -> {
System.out.println("thread2 : " + System.identityHashCode(obj.getList()));
});
thread1.start();
thread2.start();
}
private List<String> getList () {
if (list == null) {
list = new ArrayList<>();
}
return list;
}
}