我一直在使用以下代码:https://www.tutorialspoint.com/java/lang/runtime_addshutdownhook.htm-在终止时保存关键数据。但是,我收到一条错误消息:
Exception in thread "Thread-0" java.lang.NullPointerException
当我尝试返回对象的实例时,就会发生这种情况,该对象的过程已终止。为了明确起见,我正在返回的数据已初始化,即它具有一些默认值。因此,它至少应该返回默认值,而不是错误。我唯一的解释是认为这完全是因为GC。
我应该使用try{}catch{}finally{}
保存关键数据吗?还是addShutdownHook
应该可以与我描述的方法配合使用,所以我应该提供有关代码的更多信息,或者尝试在代码中查找错误?
编辑1:
以此为主要内容
public class Main {
private static Object objectInstance;
// a class that extends thread that is to be called when the program is exiting
static class Message extends Thread {
public void run() {
System.out.println("Object " + objectInstance.getTemporary()
+ " " + objectInstance.isExists());
System.out.println("Bye.");
}
}
public static void main(String[] args) {
try {
// register Message as shutdown hook
Runtime.getRuntime().addShutdownHook(new Message());
// print the state of the program
System.out.println("Program is starting...");
// call the object instances
for (int i = 0; i < 5; i++) {
System.out.println("Next...");
objectInstance = new Object(i);
}
// print that the program is closing
System.out.println("Program is closing...");
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是我的目标
public class Object {
private boolean exists = false;
private int temporary;
public Object(int temporary) {
this.temporary = temporary;
try {
Thread.sleep(3000);
// upon completion
exists = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// returns to main
public boolean isExists() {
return exists;
}
// return the index
public int getTemporary() {
return temporary;
}
}
显然,如果在该对象的第一个实例处于进程中时终止,它将抛出我在说的错误。然后,在对象的第三个实例上说,它将在前一个对象(在本例中为第二个)上打印信息。它没有保存最新实例。我应该先创建一个空的初始化程序,然后进行处理吗?显然,它因此不会将实例保存在主实例中。
答案 0 :(得分:0)
这解决了我的问题。对于主要对象:
for (int i = 0; i < 5; i++) {
System.out.println("Next...");
objectInstance = new Object(i);
System.out.println("Initialised.");
objectInstance.method();
}
对于对象:
public Object(int temporary) {
this.temporary = temporary;
}
public void method() {
try {
Thread.sleep(3000);
// upon completion
exists = true;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
谢谢!