In my understanding, a singleton object will only be destroyed when the application is about to end. Therefore, in C ++, I am writing a Singleton class to register my application and in this Singleton log destructor I am recording the time when my application was interrupted. Everything worked fine in C ++.
Now I want to have the same logger in Java as in java, there is no destructor, so I applied the finalize method to this singleton logger. But it looks like the finalize method is never called. Thus, I add that the line is System.runFinalizersOnExit(true);somewhere in my code (although I know that it is deprecated), and that the finalize method is called every time before the application terminates. But still there is a problem! If I try to write something in a file in this finalize method, this will not work, although System.out works without problems !: (
Can you guys help me solve this problem? Here is an example of the code I'm trying to do:
Singleton Logger Class:
public class MyLogger {
FileWriter writer;
private MyLogger() {
try {
this.writer = new FileWriter("log.txt");
}
catch (IOException ex) {
}
}
public static MyLogger getInstance() {
return MyLoggerHolder.INSTANCE;
}
private static class MyLoggerHolder {
private static final MyLogger INSTANCE = new MyLogger();
}
@Override
protected void finalize () {
try {
super.finalize();
System.out.println("Here");
this.writer.write(new Date().toString()+System.getProperty("line.separator"));
this.writer.write("End");
this.writer.flush();
this.writer.close();
}
catch (Throwable ex) {
}
}
public synchronized void log(String str) {
try {
this.writer.write(new Date().toString()+System.getProperty("line.separator"));
this.writer.write(str+"\n");
this.writer.flush();
}
catch (IOException ex) {
}
}
}
Main:
public class Main {
public static void main(String[] args) {
System.runFinalizersOnExit(true);
MyLogger logger = MyLogger.getInstance();
logger.log("test");
}
}
source
share