Java library for prevent running multiple instances of an application, and offer a communication with the first instance.
It's based on the use of a lock file with exclusive lock to ensure that only the first process can write into this file. For the IPC communication, a simple single thread socket server is start by the first process, and the port number is written on the lock file.
For installing using maven, add this dependency into the pom.xml
:
<dependency>
<groupId>fr.quatrevieux</groupId>
<artifactId>single-instance</artifactId>
<version>1.0</version>
</dependency>
Use SingleInstance#onAlreadyRunning()
to check if an instance is running, and send a message.
Then start the IPC server using SingleInstance#onMessages()
.
/**
* Forward the arguments to the first running application
*/
public class MyApp {
public static void main(String[] args) {
// Check if there is a running instance
SingleInstance.onAlreadyRunning(instance -> {
try {
// Forward arguments to the instance
for (String arg : args) {
instance.send("Open", arg.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
// Quit the process
System.exit(0);
});
// We are on the first running instance here : initialize application
MyApp app = new MyApp();
// Start the IPC server and consume messages
SingleInstance.onMessage(message -> {
// Handle the "Open" message
if (message.name().equals("Open")) {
app.open(new String(message.data()));
}
});
// Continue execution
for (String arg : args) {
app.open(arg);
}
}
public void open(String argument) {
// ...
}
}
This project is licensed under the LGPLv3 licence. See COPYING and COPYING.LESSER files for details.