Can I implement park / unpark methods in pure Java?

I know that LockSupport is part of the JDK, but I wonder if the implementation below is semantically correct. Note that Object.wait can solve the thread interrupt problem. My question is not about performance; however, I would be grateful for any suggestion to improve my solution so long as your solution uses only the basic design, such as waiting, notification, and synchronization.

Thank you very much.

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; } 
+4
source share
1 answer

The original resolution must be false.

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

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

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

After wait() , usually or abruptly due to an interrupt, use permission.

In unpark() , if the resolution is already true, there is no need to notify.

+2
source

All Articles