Java/File Input Output/FileLock

Материал из Java эксперт
Версия от 06:02, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Creating a File Lock on a File

 
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class Main {
  public static void main(String[] argv) throws Exception {
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
    FileLock lock = channel.lock();
    lock = channel.tryLock();
    lock.release();
    channel.close();
  }
}





Creating a Shared File Lock on a File

 
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
public class Main {
  public static void main(String[] argv) throws Exception {
    File file = new File("filename");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
    FileLock lock = channel.lock(0, Long.MAX_VALUE, true);
    lock = channel.tryLock(0, Long.MAX_VALUE, true);
    boolean isShared = lock.isShared();
    lock.release();
    channel.close();
  }
}





Preventing multiple instances of an application: The file lock technique

 
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
class JustOneLock {
  private String appName;
  FileLock lock;
  FileChannel channel;
  public JustOneLock(String appName) {
    this.appName = appName;
  }
  public boolean isAppActive() throws Exception{
    File file = new File(System.getProperty("user.home"), appName + ".tmp");
    channel = new RandomAccessFile(file, "rw").getChannel();
    lock = channel.tryLock();
    if (lock == null) {
      lock.release();
      channel.close();
      return true;
    }
    Runtime.getRuntime().addShutdownHook(new Thread() {
      public void run() {
        try {
          lock.release();
          channel.close();
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });
    return false;
  }
}
public class Main {
  public static void main(String[] args)throws Exception {
    JustOneLock ua = new JustOneLock("JustOneId");
    if (ua.isAppActive()) {
      System.out.println("Already active.");
      System.exit(1);
    } else {
      System.out.println("NOT already active.");
    }
  }
}