Last active
October 31, 2022 00:15
-
-
Save Remzi1993/234ea98293c65ffec4d10b7c70b88645 to your computer and use it in GitHub Desktop.
Example of a more advanced lock system 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.FileNotFoundException; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.nio.channels.FileChannel; | |
import java.nio.channels.FileLock; | |
/** | |
* Minimal reproducible example (MRE) - Example of a more advanced lock system. | |
* @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"); | |
if (FILE.exists()) { | |
System.err.println("The application is already running!"); | |
return; | |
} | |
try ( | |
FileOutputStream fileOutputStream = new FileOutputStream(FILE); | |
FileChannel channel = fileOutputStream.getChannel(); | |
FileLock lock = channel.lock() | |
) { | |
System.out.println("Starting application"); | |
} catch (FileNotFoundException e) { | |
throw new RuntimeException(e); | |
} 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 very simple file lock system? Check this gist out: https://gist.github.com/Remzi1993/f97a55054f3769a5d3d0d16597691f57