java thread accessing outer object before it's created
anonymous, inner-classes, java, multithreading
Solution
This is called "leaking this". Here you have the code
public class Test {
// this is guaranteed to be initialized after the constructor
private final int val;
public Test(int v) {
new Thread(new Runnable() {
@Override public void run() {
System.out.println("Val is " + val);
}
}).start();
this.val = v;
}
}
Guess what it will (may, since it's a thread) print. I used a `final` field to stress that the object is accessed before it has been fully initialized (final fields must be definitely assigned after the last line of every constructor)
How do you recover
You don't want to pass `this` around when you are in a constructor. This also mean you don't want to call non-final virtual methods in the very same class (non-static, non-private), and not using inner classes (anonymous classes are inner classes), that are implicitely linked to the enclosing instance, thus it's as they could access `this`.
Problem
Yes, this is an academic question, I know people will complain that I'm not posting any code but I'm genuinely struck with this question, really don't know where to begin. I would really appreciate an explanation and maybe some code example. If an object constructor starts a new thread that executes the method run of an anonymous inner class object, it is possible that this new thread can access its surrounding outer object before it has been fully constructed and its fields fully initialized. How would you prevent this from happening?