Unsafe.park vs Object.wait

后端 未结 4 727
我在风中等你
我在风中等你 2020-12-24 08:03

I have a couple of questions regarding Unsafe.park and Object.wait (and their corresponding resume methods):

  1. Which one should be use
4条回答
  •  别那么骄傲
    2020-12-24 08:30

    LockSupport.park/unpark has better performance, but it's too low level API.

    Besides, they have some different operations maybe you should notice:

        Object lockObject = new Object();
        Runnable task1 = () -> {
            synchronized (lockObject) {
                System.out.println("thread 1 blocked");
                try {
                    lockObject.wait();
                    System.out.println("thread 1 resumed");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
            }
        };
        Thread thread1 = new Thread(task1);
        thread1.start();
    
        Runnable task2 = () -> {
            System.out.println("thread 2 running ");
            synchronized (lockObject) {
                System.out.println("thread 2 get lock");
                lockObject.notify();
            }
        };
        Thread thread2 = new Thread(task2);
        thread2.start();
    

    In this case, thread2 can get lock and notify the thread1 to resumed, because lockObject.wait(); will release the lock.

        Object lockObject = new Object();
        Runnable task1 = () -> {
            synchronized (lockObject) {
                System.out.println("thread 1 blocked");
                LockSupport.park();
                System.out.println("thread 1 resumed");
    
            }
        };
        Thread thread1 = new Thread(task1);
        thread1.start();
    
        Runnable task2 = () -> {
            System.out.println("thread 2 running ");
            synchronized (lockObject) {
                System.out.println("thread 2 get lock");
                LockSupport.unpark(thread1);
            }
        };
        Thread thread2 = new Thread(task2);
        thread2.start();
    

    However, if you use LockSupport.park/unpark like this, it will cause dead lock. because thread1 won't release the lock by using LockSupport.park. therefore, thread1 can't resumed.

    So be careful, they have different behaviors besides blocking the thread. And in fact, there are some Class we can use it conveniently to coordinate in multi-thread environment, such as CountDownLatch, Semaphore, ReentrantLock

提交回复
热议问题