Skip to content

Instantly share code, notes, and snippets.

@bmchae
Created November 7, 2011 07:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bmchae/1344404 to your computer and use it in GitHub Desktop.
Save bmchae/1344404 to your computer and use it in GitHub Desktop.
How to lock a process in java to prevent multiple instance at the same time
http://www.dscripts.net/2010/06/09/how-to-lock-a-process-in-java-to-prevent-multiple-instance-at-the-same-time/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// check if another process is running
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
package utils;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
/**
*
* @author Burhan Uddin
*/
public class lock {
private static File f;
private static FileChannel channel;
private static FileLock lock;
public lock()
{
try
{
f = new File("process.lock");
// Check if the lock exist
if (f.exists()) // if exist try to delete it
f.delete();
// Try to get the lock
channel = new RandomAccessFile(f, "rw").getChannel();
lock = channel.tryLock();
if(lock == null)
{
// File is lock by other application
channel.close();
throw new RuntimeException("Two instance cant run at a time.");
}
// Add shutdown hook to release lock when application shutdown
ShutdownHook shutdownHook = new ShutdownHook();
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
catch(IOException e)
{
throw new RuntimeException("Could not start process.", e);
}
}
public static void unlockFile() {
// release and delete file lock
try
{
if(lock != null)
{
lock.release();
channel.close();
f.delete();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
static class ShutdownHook extends Thread {
public void run() {
unlockFile();
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
package msngr;
import utils.lock;
public class Main {
public static void main(String[] args) {
.....
lock l = new lock();
....
}
}
@Zoommeerrss
Copy link

awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment