St.Antario St.Antario - 1 year ago 85
Java Question

Understanding alien methods in Java concurrency

I'm reading J. Bloch's effective Java and now I'm at the section about alien methods.

I'm trying to understand alien methods in Java concurrency and the harm they could do. As he said, we basically don't know what alien methods could do and we may end up deadlocking. I tried to reproduce such a deadlocking behavior writing the following simple app (The alien method is in the same class for simplicity):

public class App {
private static StringBuffer lines = new StringBuffer();

public static void modifyLines(){
System.out.println("Invocation modifyLines() started by " + Thread.currentThread().getName());
synchronized (lines) {
System.out.println("Entering modifyLines() synchronized " + Thread.currentThread().getName());
lines.append("Modified");
}
}

public static void main(String[] args) throws InterruptedException {
synchronized (lines) {
System.out.println("Entering main() synchronized by " + Thread.currentThread().getName());
alienMethod();
}
}

public static void alienMethod(){
ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(new Runnable() {
@Override
public void run() {
modifyLines();
}
});
es.shutdown();
}
}


I expected a deadlock to take place and that the thread spawned by calling to
alienMethod()
would never enter the synchronized block within
modifyLines()
. But the program prints the following:

Entering main() synchronized by main
Invocation modifyLines() started by pool-1-thread-1
Entering modifyLines() synchronized pool-1-thread-1


Which means the deadlock did not happen. Why? What's wrong with the alien method example?

Answer Source

Your alienMethod() does not wait till the submitted task is finished. If you wait for it, you will have a deadlock:

public static void alienMethod() throws InterruptedException{
    ExecutorService es = Executors.newSingleThreadExecutor();
    es.submit(new Runnable() {
        @Override
        public void run() {
            modifyLines();
        }
    });
    es.shutdown();
    es.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download