Yet More Programming Puzzlers

Tags:

Yet More Programming Puzzlers: TS-3738, 2005

by Joshua Bloch and Neal Gafter.

Joshua는 Effective JAVA를 쓴 유명인물이죠. 그 책에서 finalize guardian을 대중에게 소개했고요. 음. 이 프리젠테이션의 내용은 다 감탄할 만하지만, 그 중에서도 큰 박수를 받은 Lazy Initialization의 코드를 적어보겠습니다.

[quote]

public class Lazy {

    private static boolean initialized = false;

    static {
        Thread t = new Thread(new Runnable() {
            public void run() {
                initialized = true;
            }
        });

        t.start();

        try { t.join();
        }
        catch(InterruptedException ie) {
            throw new AssertionError(ie);
        }
    }

    public static void main(String[] args) {
        System.out.println(initialized);
    }
}

[/quote]

실행결과는 어떻게 될까요?

(1) true
(2) false
(3) It varies.
(4) None of the above.

답은 4번입니다. 이 코드는 모든 자바 플랫폼에서 deadlock이 걸립니다. 그 이유는 다음과 같습니다.

(1) main thread가 Thread t를 run 하고 join에서 대기한다.
(2) t는 run에서 initialized를 본다. 그리고 initialized가 초기화되는 것을 기다린다. 일단 초기화가 되야 자기가 쓸 수 있으니까.
(3) 그런데, initialized는 현재 main thread에서 초기화중이다. 따라서 t는 main thread를 기다린다.
(4) 한편 main thread는 t에 join하고 있다.

이에 대한 해결책은 background thread를 사용한 초기화를 피하라는 것입니다.

p.s. Joshua도 이젠 구글의 사람이군요.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *