package semaphore;

import javax.swing.JOptionPane;

/**
 * ファイルを使用した擬似セマフォの利用.
 * http://d.hatena.ne.jp/Kazzz/20071217/p1
 */
public class PseudoFileSemaphoreTest {

	private static final String SEMAPHORE_NAME = "PseudoFileSemaphore";

	private static final int SEMAPHORE_PERMITS = 1;

	/**
	 * アプリケーション起動.
	 * @param args コマンド引数
	 * @throws Exception 例外
	 */
	public static void main(String[] args) throws Exception {
		final PseudoFileSemaphore semaphore = new PseudoFileSemaphore(SEMAPHORE_NAME, SEMAPHORE_PERMITS);

		// シャットダウンフック
		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
			@Override
			public void run() {
				semaphore.release();
			}
		}));

		if (semaphore.acquire()) {
			// 起動OK!
			JOptionPane.showMessageDialog(null, "アプリケーションを起動しました。",
					SEMAPHORE_NAME, JOptionPane.INFORMATION_MESSAGE);
		} else {
			// 起動NG!
			JOptionPane.showMessageDialog(null, "アプリケーションの起動上限に達しました。",
					SEMAPHORE_NAME, JOptionPane.ERROR_MESSAGE);
		}
	}

}
