Achieving Single Instance Applications in Java
In contrast to certain applications like MSN and Windows Media Player, which only create a single instance when executed while running, Java applications may spawn multiple instances. In this article, we'll explore how to create single instance Java applications using the proven method described below.
Java Approach
Unlike C# where the Mutex class handles this functionality, Java utilizes a distinct approach:
private static boolean lockInstance(final String lockFile) { try { final File file = new File(lockFile); final RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw"); final FileLock fileLock = randomAccessFile.getChannel().tryLock(); if (fileLock != null) { Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { try { fileLock.release(); randomAccessFile.close(); file.delete(); } catch (Exception e) { log.error("Unable to remove lock file: " + lockFile, e); } } }); return true; } } catch (Exception e) { log.error("Unable to create and/or lock file: " + lockFile, e); } return false; }
The above is the detailed content of How to Ensure Only One Instance of a Java Application Runs at a Time?. For more information, please follow other related articles on the PHP Chinese website!