Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java applet: How to make sure destroy is finished before page refresh

In Java util logging, I initiate the handler on init(), and close the handler at destroy() and it works perfectly fine: A log file was created, etc. If the user refreshs the page normally, it still just creates one log file.

However if the user refreshs the page with the applet a couple of times fast, it seems like the destroy() does not get called or maybe hasn't finished the task and since the init() gets called again, it assumes the previous file is still locked and creates a new log file.

I tried to use both destroy() and finalize() to close the handler but it does not work. Anyone has any idea how to solve this issue?

Another minor question is: What actually happened if init() has not finished and the page gets refreshed. Is it going to continue the process and eventually failes to call destroy() or does it just stop right there?

like image 314
Harts Avatar asked Oct 08 '22 04:10

Harts


1 Answers

Quote from Java Tutorials:

The Java Plug-in software creates a worker thread for every Java applet .

In multithreaded environment you should be very careful with shared resources. Best and easiest approach is not to share anything (scales best and no deadlocks possible).

I assume, that you initialize your handler each time in "init"-method. If it's true, you should use one static shared logger (check this link). It will help to improve situation a bit, but if you start more than one browser with your applet - new log file still will be created. And this workaround is not recommended by Oracle and preserved for backward compatibility.


Recommended and easy to implement solution - "each applet should have it's own logger and write to own file". Code for log file name generation:

private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

private String generateFileName() {
    return String.format("applets-log/%s-%s.log", dateFormat.format(new Date()), UUID.randomUUID());
}

Also, Best Practices For Applet Development.


Answer to your minor question (changed):

According to discussion of this old bug in java plugin, applet could be terminated at any moment with some predefined interval for cleanup. So you should put resource cleanup code in your "stop" or "destroy" method, but you shouldn't rely what that code will be executed.

Applets lifecycle is controlled by browser and applets should not be given capabilities to run when its hosting document is destroyed by browser.

Since 6u10, both old plugin and new plugin enforce applet shutdown after a fixed amount of time (1000ms in old plugin and 200ms in new plugin) for applet to stop.

like image 101
Vadim Ponomarev Avatar answered Oct 19 '22 03:10

Vadim Ponomarev