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
  • 973
  • 1
  • 6
  • 13

3 Answers3

4

Because ReentrantLock lock; is never instantiated/initialized.

Initialize it at the beginning.

ReentrantLock lock = new ReentrantLock();
Buhake Sindi
  • 85,564
  • 27
  • 164
  • 223
0

You need to init the object of the ReentrantLock class

doing:

ReentrantLock lock = new ReentrantLock();
ΦXocę 웃 Пepeúpa ツ
  • 45,713
  • 17
  • 64
  • 91
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
  • 352
  • 4
  • 15