Skip to content

Instantly share code, notes, and snippets.

@hirofumi
Created May 15, 2013 04:25
Show Gist options
  • Save hirofumi/5581640 to your computer and use it in GitHub Desktop.
Save hirofumi/5581640 to your computer and use it in GitHub Desktop.
Java で多重起動を検出する方法

ソケットを使う

Swing Hacks の "Hack 84. Construct Single-Launch Applications" などで紹介されている方法です。

static final int LOCK_PORT = 38629;
ServerSocket serverSocket = null;
try {
  serverSocket = new ServerSocket(LOCK_PORT);
  // 多重起動ではなかった
} catch (IOException e) {
  // 多重起動だった
}

ファイルロックを使う

JAVAの二重起動防止は可能? などで紹介されている方法です。

FileOutputStream fos = new FileOutputStream("/path/to/file-to-lock");
FileChannel fc = fos.getChannel();
FileLock fl = fc.tryLock();
if (fl == null) {
  // 多重起動だった
} else {
  // 多重起動ではなかった
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment