Java try-finally语法中的NPE
下面是我测试一些语法的代码。我想在try块中返回一个对象,并在finally块中执行一些操作。但是当我运行代码时,我得到了NullPointException。原因是使用了Java try-finally语法中的NPE,java,Java,下面是我测试一些语法的代码。我想在try块中返回一个对象,并在finally块中执行一些操作。但是当我运行代码时,我得到了NullPointException。原因是使用了ReentrantLock,但我不知道为什么 import java.util.concurrent.locks.ReentrantLock; public class Main { ReentrantLock lock; public static void main(String[] args) {
ReentrantLock
,但我不知道为什么
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;
}
}
如果我取消注释lock.lock()
和lock.unlock()
,我将得到NullPointException。
为什么?因为
可重入锁定锁代码>从未实例化/初始化
在开始时初始化它
ReentrantLock lock = new ReentrantLock();
因为ReentrantLock锁代码>从未实例化/初始化
在开始时初始化它
ReentrantLock lock = new ReentrantLock();
您需要初始化ReentrantLock类的对象
做:
ReentrantLock lock = new ReentrantLock();
您需要初始化ReentrantLock类的对象
做:
ReentrantLock lock = new ReentrantLock();
按如下方式初始化锁变量:
private final ReentrantLock lock = new ReentrantLock();
基本上会引发NullPointException,因为锁是用null值初始化的,所以这就是为什么应该初始化的原因。像这样初始化锁变量:
private final ReentrantLock lock = new ReentrantLock();
基本上会引发NullPointException,因为锁是用null值初始化的,所以应该初始化