Domanda

I know LockSupport is part of the JDK, but I am wondering if the implementation below is semantically correct. Observe that Object.wait can deal with the problem of thread's interrupt. My question is not regarding performance; however, I will appreciate any suggestion to improve my solution as long as your solution only uses basic construction like wait, notify and synchronized.

Thanks a lot.

final class LockSupport {
    static void park(long time) {
        Thread th = Thread.currentThread();
        if (th instanceof MyThread) {
            MyThread h = (MyThread)th;
            synchronized (h.obj) {
                if (h.permit) {
                    h.permit = false;
                    return;
                }
                try {
                    h.obj.wait(time);
                } catch (InterruptedException e) { }
            }
        }
    }

    static void unpark(MyThread h) {
        synchronized (h.obj) {
            h.permit = true;
            h.obj.notify();
        }
    }
}

abstract class MyThread extends Thread {
    public Object obj = new Object();
    public boolean permit = true;
}
È stato utile?

Soluzione

Initial permit should be false.

When an interrupt is caught, you need to re-interrupt the current thread

 catch (InterruptedException e) { th.interrupt(); }

because if park() returns due to interrupt, the interrupt status should be set (see javadoc example)

After wait() completes, normally or abruptly due to interrupt, consume the permit.

In unpark(), if permit is already true, there's no need to notify.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top