2016-03-04 37 views
0

以下是我測試某些語法的代碼。我想在try-block中返回一個對象,並在finally塊中做一些事情。但是當我運行我的代碼時,我得到NullPointException。原因是使用ReentrantLock,但我不知道爲什麼。NPE in try-finally grammar

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。 爲什麼?

回答

4

因爲ReentrantLock lock;從來沒有實例化/初始化。

在開頭初始化它。

ReentrantLock lock = new ReentrantLock(); 
0

你需要給init 的ReentrantLock

的對象做:

ReentrantLock lock = new ReentrantLock(); 
0

初始化這樣的鎖變量:

private final ReentrantLock lock = new ReentrantLock(); 

基本上NullPointException是因爲拋出鎖被初始化爲空值,所以這就是爲什麼你應該初始化。