onsen code monkey

個人的な日記とプログラミング備忘録です

【Java】ファイルロックで排他制御

よく使うのでメモ

File lockFile = new File(fName + ".lock");
lockFile.deleteOnExit();

try (FileOutputStream fs = new FileOutputStream(lockFile)){
	FileChannel ch = fs.getChannel();
       	FileLock lock = null;

        for (int i = 0; i < (TIMEOUT / WAIT); i++) {
            if (null != (lock = ch.tryLock())) {
                break;
            }
            Thread.sleep(WAIT);
        }
        if (null == lock) {
       	    throw new Exception();
        }
    	try (FileOutputStream fos = new FileOutputStream(file);
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos,"EUC-JP"));){
    		writer.write(temp.toString());
    		writer.flush();
        	} catch(Exception ex) {
    			throw ex;
    		} finally {
                // ロックファイルを開放する
                lock.release();
                ch.close();
    		}
		} catch (Exception e) {
			throw new LogicException();
		} finally {
                         lockFile.delete();
		}