Tuesday, February 24, 2015

Guaranteeing that single instance runs at the same time

public class BgwBufferRetry {

        public static void main(String[] args) throws Exception {
                if (isAnotherInstanceRunning())
                        return;
        }
       
        private static boolean isAnotherInstanceRunning(){
                try{
                    RandomAccessFile randomFile = new RandomAccessFile("ClassName.class","rw");
                    FileChannel channel = randomFile.getChannel();

                    if(channel.tryLock() == null) {
                        System.out.println("Already Running...");
                        return true;
                    }
                }catch( Exception e ) {
                        System.out.println(e.toString());
                    return true;
                }
                return false;
        }
}

No comments:

Post a Comment