I'm trying to understand how does final
field acts in multi-threaded environment.
I read these related posts:
final fields and thread-safety
Java concurrency: is final field (initialized in constructor) thread-safe?
Java: Final field freeze on object reachable from final fields
and tried to simulate situation where final
field will prevent threads from working with not fully constructed object.
public class Main {
public static void main(String[] args) {
new _Thread().start();
new Dummy();
}
static class _Thread extends Thread {
static Dummy dummy;
@Override
public void run() {
System.out.println(dummy.getIntegers().size() == 10_000);
}
}
static class Dummy {
private final List<Integer> integers = new ArrayList<>();
public Dummy() {
_Thread.dummy = this;
for (int a = 0; a < 10_000; a++) {
integers.add(a);
}
}
public List<Integer> getIntegers() {
return integers;
}
}
}
So as I understood, _Thread
will stop execution on getIntegers()
and wait until loop finish filling collection. But whether there is a final
modifier or not on field integers
, result of run()
is unpredictable. Also I know that there is a possibility of NPE.