Lightweight Kotlin/JVM library that prevents multiple concurrent instances of a Kotlin application. Launch arguments from subsequent instances are communicated back to the first instance via a UNIX domain socket.
A Kotlin equivalent to unique4j
Add the jitpack repository to your build file:
repositories {
maven { url 'https://jitpack.io' }
}
Then add as a module dependency:
dependencies {
implementation("com.github.iamcalledrob:singleinstance:1.0.3")
}
Instantiate SingleInstance
with a file path and call args()
.
- If this is the first instance,
args
will listen indefinitely for subsequent instances to connect to it. - If there is an existing instance,
args
will connect and send its arguments, then exit.
fun main(args: Array<String>) {
SingleInstance("/path/to/a/unique/file.sock").args(args) { receivedArgs ->
// Handle received args from another instance
println("Subsequent instance args: ${receivedArgs.joinToString()}")
}
// Handle original args
println("Original launch args: ${args.joinToString()}")
// The rest of the application logic
}
There is also a helper function for generating a suitable sock file path from an identifier:
socketPath(identifier = "org.foo.widget")
// -> /tmp/org.foo.widget.sock
- A system-wide file lock is used to determine which instance is "first" to launch
- The first instance then listens on a domain socket for arguments from other instances
- Other instances are unable to acquire the file lock, and instead connect to the first instance via the socket. Arguments are written to the socket, then the process exits.
- When the original process exits, the file lock is released.
Why you might consider this over unique4j
- Uses UNIX Domain Sockets, which avoids triggering the Windows firewall. unique4j listens on a local TCP socket, which will pop a firewall dialog.
- Minimal design, leaves the exact implementation up to you.
- Filesystem permissions can be used to control which processes are able to send arguments, if desired.
Domain sockets were added to Windows version 1809, so this library is unsuitable for legacy versions of Windows.