001/* 002 * Copyright 2010-2015 Institut Pasteur. 003 * 004 * This file is part of Icy. 005 * 006 * Icy is free software: you can redistribute it and/or modify 007 * it under the terms of the GNU General Public License as published by 008 * the Free Software Foundation, either version 3 of the License, or 009 * (at your option) any later version. 010 * 011 * Icy is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 014 * GNU General Public License for more details. 015 * 016 * You should have received a copy of the GNU General Public License 017 * along with Icy. If not, see <http://www.gnu.org/licenses/>. 018 */ 019package icy.system; 020 021import icy.file.FileUtil; 022 023import java.io.File; 024import java.io.FileOutputStream; 025import java.io.IOException; 026import java.nio.channels.FileLock; 027 028/** 029 * Class to verify we have a single instance of an object or whatever (use {@link FileLock}). 030 * 031 * @author Stephane 032 */ 033public class SingleInstanceCheck 034{ 035 public static FileLock lock(String id) 036 { 037 FileLock result; 038 final File f = new File(FileUtil.getTempDirectory() + FileUtil.separator + id + ".lock"); 039 040 try 041 { 042 result = new FileOutputStream(f).getChannel().tryLock(); 043 } 044 catch (Exception e) 045 { 046 result = null; 047 } 048 049 return result; 050 } 051 052 public static boolean release(FileLock lock) 053 { 054 if (lock != null) 055 { 056 try 057 { 058 lock.release(); 059 return true; 060 } 061 catch (IOException e) 062 { 063 // ignore 064 } 065 } 066 067 return false; 068 } 069}