The following code is puzzling me a lot.
import java.util.function.Predicate;
public class Test {
private final Predicate<String> filter = s -> s != null;
private boolean started = false;
private class Runner implements Runnable {
@Override
public void run() {
synchronized ( Test.this ) {
started = true;
Test.this.notifyAll();
traverse("");
}
}
}
public Test() {
System.out.println(filter.test(""));
Thread thread = new Thread(new Runner());
thread.setDaemon(true);
thread.start();
}
public synchronized String start() {
while ( !started ) {
try {
wait();
} catch ( InterruptedException ex ) {}
}
return "";
}
private synchronized void traverse(String s) {
filter.test(""); // DOES NOT COMPUTE
filter.test(s);
System.out.println("not here");
}
private static final String STRING = new Test().start(); // POS1
public static void main(String[] args) {
System.out.println(STRING); // POS2
}
}
It gets stuck at DOES NOT COMPUTE
. If, however, I delete the line POS1
and alter POS2
to System.out.println(new Test().start())
it runs flawlessly. In above code, filter
appears to not evaluate if Test
gets initiated though the static variable.
Why is this the case and how can it be fixed please?