Skip to content

Java library for prevent running multiple instances of an application, and offer a communication with the first instance.

License

LGPL-3.0, GPL-3.0 licenses found

Licenses found

LGPL-3.0
COPYING.LESSER
GPL-3.0
COPYING
Notifications You must be signed in to change notification settings

vincent4vx/SingleInstance

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SingleInstance

Build Status Scrutinizer Code Quality Code Coverage javadoc Maven Central

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.

Installation

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>

Usage

Basic usage

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) {
        // ...
    }
}

Licence

This project is licensed under the LGPLv3 licence. See COPYING and COPYING.LESSER files for details.

About

Java library for prevent running multiple instances of an application, and offer a communication with the first instance.

Topics

Resources

License

LGPL-3.0, GPL-3.0 licenses found

Licenses found

LGPL-3.0
COPYING.LESSER
GPL-3.0
COPYING

Stars

Watchers

Forks

Packages

No packages published

Languages