Reputation: 927
I am using java.mail jar file version 1.4.7
I created a Window's scheduler to load emails from email server. This scheduler is run every 7 minutes. At the end of the code, for those emails that were loaded, system will delete them from the email server.
This supposes to work but if the previous instance takes more than 7 minutes to load the emails, another new instance could load the same email because the first instance have not run the code to delete the email.
I think this is a concurrency issue.
I have tried a few solutions:
synchronized
keyword to the method.isrun
. Before any instance run the method, it need to verify whether isrun == false
. If false, then the system will run the method; if true, then it will bypass all of the code. After the instance finishes running the method, it will update the isrun
checkbox to false again.These methods do help but they are not workable if the size of the emails are too large. (Possible they have a lot of attachments.)
Do you have any idea on how to solve this?
Upvotes: 0
Views: 84
Reputation: 831
I presume that the Windows Scheduler event fires off a new instance of the Java application. In that case you need to use some kind of external locking. Perhaps creating a lock file. The process checks if a locking file exists and if not creates one and then continues. A second process would detect this file and have to wait or abort. Once the process is finished it removes the lock file. You need to be careful of how the file locking is implemented so that processes. You have to implement the locking carefully though so that multiple processes don't just check for a file (at the same time), see it's not there and then both try to create it. This shouldn't be a problem as your processes won't be starting at the same time but should be considered. Examples shown here:
How can I lock a file using java (if possible)
Another solution would be to have the Java application running constantly and every seven minutes run the update. This way the synchronization can be performed internally. The main part of the application would sit in a loop and wait for seven minutes to pass and then run your update routine (method). This would required some kind of daemon thread running. Apache has this but it takes a bit of work to get it up and running.
http://commons.apache.org/proper/commons-daemon/
There is also an option in the scheduler to not run in parallel. This is probably the easiest option. Look in the Settings tab of the task properties at the bottom (Win 8). You can tell it not to start or to wait if there is an instance already running.
Upvotes: 1