I want to close all FileHandler
s once the thread finished or was forcely finished.
I created a closeLogger
function but it seems it's not being called
because I see that the file is still locked in the folder.
- What is the problem?
- Can I also handle it if I forcely terminated the execution in eclipse?
My code is as follows:
public class Passenger extends Thread {
private Logger logger;
public Passenger() throws SecurityException, IOException, InterruptedException {
logger = Logger.getLogger(String.format("Passenger%sLogger", name));
FileHandler fileHandler = new FileHandler(String.format(".\\Logs\\PassengerLogs\\passenger_%s.txt", name), true);
fileHandler.setFormatter(new LogFormatter());
logger.addHandler(fileHandler);
}
@Override
public void run() {
try {
goToStation();
waitForTaxi();
if (passengerState == PassengerState.WatingInQueue) {
goHome();
} else { // already in taxi
synchronized (this) {
wait();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
closeLogger();
}
}
private void closeLogger() {
Logger logger = getLogger();
java.util.logging.Handler[] handlers = logger.getHandlers();
for (java.util.logging.Handler h : handlers) {
try {
h.close();
} catch (SecurityException e) {}
}
}
}
Since you are adding handler using addHandler(), clean way is to close() and then call removeHandler()
See removeHandler
Also, copied from above link:
So if you are not removing handler, it will still hold reference. This may be the reason why your file is still locked. Try this and let me know if it works!