I need to prevent a certain application function from being run concurrently with itself. The risk is significant because this function is in code submitted to java.util.Timer (to repeat every minute for several hours) and the process that sets up the function completes and goes back to the bash command line. The user might then invoke the same program. Another risk is from the user that has two or more console windows and they mistakenly run the program in both console windows.
I think an operating system-wide semaphore with a Java API might do the trick. Is there such a Java archive available?
I was asked if multiple JVMs are used. I think if multiple consoles are opened then multiple JVMs are implied.
This is my wrapper to use Java’s Timer and TimerTask.
public final class TimedExecutorWrapper
{ ... various private members ...
public Timer go()
{
Timer myTimer = new Timer();
myTimer.scheduleAtFixedRate(this.myTask,
this.startTodayAtThisTime,
this.frequencyInSeconds * 1000);
TimerTask myTaskToInvokeCancel = new TaskToInvokeCancel(myTimer);
// use the same Timer to schedule the task that cancels and purges
myTimer.schedule(myTaskToInvokeCancel,
this.stopTodayAtThisTime);
return myTimer;
}
private final class TaskToInvokeCancel extends TimerTask
{
private Timer timer; // to be cancelled and purged
TaskToInvokeCancel(Timer timer)
{
this.timer = timer;
}
public void run()
{
this.timer.cancel(); // discards any scheduled tasks without
// interfering with any running task
this.timer.purge();
}
}
}
You could create a 0 byte file ‘methodname.LOCK’ in a shared directory when you begin the operation, and delete it when you are done. Creating it with a no recreate flag in Java should solve your problem.
Make sure to delete it in a ‘finally’ block so you are never left in a state where the file exists and continues to block the process from ever running