All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fr.dyade.aaa.agent.ServerLock Maven / Gradle / Ivy

There is a newer version: 5.22.0-EFLUID
Show newest version
/*
 * Copyright (C) 2024 ScalAgent Distributed Technologies
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA.
 *
 * Initial developer(s): ScalAgent Distributed Technologies
 * Contributor(s): 
 */
package fr.dyade.aaa.agent;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

import fr.dyade.aaa.common.Debug;

public class ServerLock {
  private static Logger logmon = Debug.getLogger(AgentServer.class.getName());

  private RandomAccessFile raf;
  private FileLock lock;
  
  public ServerLock(File file) throws IOException {
    raf = new RandomAccessFile(file, "rw");
    lock = raf.getChannel().tryLock();
    if (lock == null)
      throw new IOException("Cannot acquire lock.");
    file.deleteOnExit();
  }

  public void check() {
    if (lock != null)
      logmon.log(BasicLevel.WARN, "AgentServer.lock -> " + lock.isValid() + '/' + lock.isShared());
  }
  
  public void close() {
    try {
      if (lock != null)
        lock.release();
    } catch (IOException exc) {
      if (logmon.isLoggable(BasicLevel.DEBUG))
        logmon.log(BasicLevel.WARN, "Cannot release AgentServer lock.", exc);
      else
        logmon.log(BasicLevel.WARN, "Cannot release AgentServer lock: " + exc.getMessage());
    } finally {
      lock = null;
    }
    try {
      if (raf != null)
        raf.close();
    } catch (IOException exc) {
      if (logmon.isLoggable(BasicLevel.DEBUG))
        logmon.log(BasicLevel.WARN, "Cannot close AgentServer lock.", exc);
      else
        logmon.log(BasicLevel.WARN, "Cannot close lock: " + exc.getMessage());
    } finally {
      raf = null;
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy