- RandomAccessFile 로 lock 건 상태로 파일 쓰기
private static void test() {
try {
String resultname = "test.text";
RandomAccessFile stream = new RandomAccessFile(resultname, "rw");
FileChannel channel = stream.getChannel();
FileLock lock = null;
try {
lock = channel.tryLock();
System.out.println("lock 유효성 : " + lock.isValid());
BufferedWriter bw = new BufferedWriter(Channels.newWriter(channel, "UTF-8"));
bw.write("파일에 lock 걸고 쓰는 중ㅡㅡㅡㅡ");
bw.flush();
Thread.sleep(5000L);
bw.close();
} catch (OverlappingFileLockException e) {
e.printStackTrace();
} finally {
if (lock != null && lock.isValid()) {
lock.release();
}
if (channel.isOpen()) {
channel.close();
}
stream.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("끝");
}
- release 하지 않은 상태에서 타 스레드, 프로세스에서 해당 파일에 접근하면 Exception 발생