View on GitHub

Application Locker

Provides file-based locking mechanism with inter-process communication support

Open library documentation Download this project as a .jar file Download this project as a Maven/Gradle dependency

AppLocker

Build Status Coverage

AppLocker is a small library which provides the often missing single instance functionality.

Features

Quick Start

The usage flow typically looks like this:

To get the AppLocker you must invoke static AppLocker#create method.

This call will return AppLocker.Builder instance with a set of #set and #on methods.

All methods are optional and have sane defaults.

#set methods allow congiguring interactions with filesystem and how AppLocker will handle incoming messages in case it was able to successfully acquire the lock.

AppLocker locker = AppLocker.create("lockID")
    .setPath(Paths.get(""))                // where to store locks (default: "")
    .setIdEncoder(this::encode)             // map `lockID` to filesystem name (default: "SHA-1")
    .setMessageHandler(msg -> process(msg)) // handle messages (default: NULL) 

#on methods allow handling errors that may occur during the AppLocker#lock call.

AppLocker locker = AppLocker.create("lockID")
    .onSuccess(this::logLocking)       // success callback (default: NULL)
    .onBusy(message, this::logAndExit) // send message to the instance which currently owns the lock and invoke callback (default: NULL)
    .onFail(this::logErrorAndExit)     // serious error happened during the lock (default: re-throw exception)

Invoke #build method to finish the building procedure and retrieve AppLocker:

AppLocker locker = AppLocker.create("lockID").build();

If you don’t want to use the #on methods, you can handle exceptions directly:

AppLocker locker = AppLocker.create("lockID").build();
try {
    locker.lock();
} catch (LockingBusyException ex) {
} catch (LockingException ex) {
}

More details can be found in JavaDocs.

Download

Maven:

<dependency> 
    <groupId>io.github.sanyarnd</groupId> 
    <artifactId>app-locker</artifactId>
    <version>1.2.0</version>
</dependency>

Gradle:

compile 'io.github.sanyarnd:app-locker:1.1.2'

Standalone jars are available on releases page.

More download options available in Bintray repository.

Changelog

See CHANGELOG.md.