J'utilise un FileLock sur un fichier commun. Cette Application ne peut pas être démarrée plusieurs fois:
import java.awt.event.*; import java.io.*; import java.nio.channels.*; import javax.swing.*; public class Main {
private FileChannel channel; private FileLock lock; private boolean blocked;
public Main() { try { channel = new RandomAccessFile(new File("MainLock.txt"), "rw").getChannel(); lock = channel.tryLock(); if (lock == null) { blocked = true; } } catch (Exception e) { blocked = true; } if (!blocked) { JFrame f = new JFrame(); f.setSize(400, 300); f.setVisible(true); f.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent e) { exit(); } }); } }
protected void exit() { try { lock.release();// Release the lock channel.close();// Close the file } catch (Exception e) { e.printStackTrace(); } System.exit(0); } public static void main(String[] args) { new Main(); } }
|