Last active
October 31, 2022 00:12
-
-
Save Remzi1993/f97a55054f3769a5d3d0d16597691f57 to your computer and use it in GitHub Desktop.
Example of a simple lock file in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package YOUR_PACKAGE_NAME; | |
import java.io.File; | |
import java.io.IOException; | |
/** | |
* Minimal reproducible example (MRE) - Example of a simple lock file. | |
* @author Remzi Cavdar - [email protected] - <a href="https://github.com/Remzi1993">@Remzi1993</a> | |
*/ | |
public class Main { | |
public static void main(String[] args) { | |
/* | |
* Prevents the user of starting multiple instances of the application. | |
* This is done by creating a temporary file in the app directory. | |
* The temp file should be excluded from git and is called App.lock in this example. | |
*/ | |
final File FILE = new File("App.lock"); | |
try { | |
if (FILE.createNewFile()) { | |
System.out.println("Starting application"); | |
} else { | |
System.err.println("The application is already running!"); | |
return; | |
} | |
} catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
/* | |
* Register a shutdown hook to delete the lock file when the application is closed. Even when forcefully closed | |
* with the task manager. (Tested on Windows 11 with JavaFX 19) | |
*/ | |
FILE.deleteOnExit(); | |
// Whatever your app is supposed to do | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Interested in a slightly more advanced locking system? Check this gist out: https://gist.github.com/Remzi1993/234ea98293c65ffec4d10b7c70b88645