Skip to content

Instantly share code, notes, and snippets.

@Remzi1993
Last active October 31, 2022 00:12
Show Gist options
  • Save Remzi1993/f97a55054f3769a5d3d0d16597691f57 to your computer and use it in GitHub Desktop.
Save Remzi1993/f97a55054f3769a5d3d0d16597691f57 to your computer and use it in GitHub Desktop.
Example of a simple lock file in Java
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
}
}
@Remzi1993
Copy link
Author

Interested in a slightly more advanced locking system? Check this gist out: https://gist.github.com/Remzi1993/234ea98293c65ffec4d10b7c70b88645

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