0

Following is my code to test some grammar. I want return a object in try-block and do something in finally-block. But I get NullPointException when I run my code.The cause is using ReentrantLock, but I don't know why.

import java.util.concurrent.locks.ReentrantLock;


public class Main {

  ReentrantLock lock;

  public static void main(String[] args) {
    try {
      new Main().run();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void run() {
      System.out.println(returnTest().get());
  }

  A returnTest(){
//  lock.lock();
    try {
      return new A();
    } finally {
//  lock.unlock();
    }
  }

}

class A {
  public boolean get() {
    return true;
  }
}

If I uncomment lock.lock() and lock.unlock(), I will get NullPointException. Why?

Zephyr Guo
  • 1,083
  • 1
  • 8
  • 14

3 Answers3

4

Because ReentrantLock lock; is never instantiated/initialized.

Initialize it at the beginning.

ReentrantLock lock = new ReentrantLock();
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
0

You need to init the object of the ReentrantLock class

doing:

ReentrantLock lock = new ReentrantLock();
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Initialize lock variable like this:

private final ReentrantLock lock  = new ReentrantLock();

Basically NullPointException is thrown because lock is initialized with null value, so that's why you should initialize.

Ardi Goxhaj
  • 362
  • 2
  • 15