Performance hit opening and closing filehandler?

。_饼干妹妹 提交于 2019-12-12 04:57:01

问题


I have a persistent event-driven HTTP upload program (hot folder) that writes to a log on every action. It runs indefinitely until the user decides to close it.

To ensure the log is closed when the application is closed, I have written the program so on every write to log, it opens the log file, writes to it, and then closes the log.

Like so:

fh = new FileHandler(logName, true);
fh.setFormatter(new MyCustomFormatter());
logger.addHandler(fh);
logger.info(message);
logger.removeHandler(fh);
fh.close();

Recently, I have considered reducing the number of open/closes by opening the log for the duration of an upload job (potentially hundreds of writes to the log) and then closing when the job is done.

Long story short, how much of a performance gain would I expect from this? Are there other options to ensuring the application closes without an unclosed log file?


回答1:


By closing the FileHandler you might be paying the cost of a sync.

If you leave your FileHandler attached to a logger at the time the JVM is shutdown the LogManager will close the log file. If you remove the handler from the logger you are responsible for closing it. If your logger is garbage collected before shutdown then the FileHandler is not closed. This type of 'file litter' can be corrected through changes to your code.

If your JVM crashes or there is an I/O exception related to closing of the log/lck file then you will see lck files left over and log files that may not contain your formatter tail string. That case is rare but, there is no way to prevent it. You have to apply a detect and correct strategy to get rid of these cases.



来源:https://stackoverflow.com/questions/25293309/performance-hit-opening-and-closing-filehandler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!