当前位置: 首页>>代码示例>>Java>>正文


Java FileLock类代码示例

本文整理汇总了Java中java.nio.channels.FileLock的典型用法代码示例。如果您正苦于以下问题:Java FileLock类的具体用法?Java FileLock怎么用?Java FileLock使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


FileLock类属于java.nio.channels包,在下文中一共展示了FileLock类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: release

import java.nio.channels.FileLock; //导入依赖的package包/类
private static void release(String lockName, FileLock fileLock, File file, Closeable stream) {
    synchronized (LOCK_MAP) {
        if (fileLock != null) {
            try {
                LOCK_MAP.remove(lockName, fileLock.hashCode());
                ConcurrentHashMap<Integer, ProcessLock> locks = LOCK_MAP.get(lockName);
                if (locks == null || locks.isEmpty()) {
                    IOUtil.deleteFileOrDir(file);
                }

                if (fileLock.channel().isOpen()) {
                    fileLock.release();
                }
            } catch (Throwable ex) {
                LogUtil.e(ex.getMessage(), ex);
            } finally {
                IOUtil.closeQuietly(fileLock.channel());
            }
        }

        IOUtil.closeQuietly(stream);
    }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:24,代码来源:ProcessLock.java

示例2: incrementNextTaskId

import java.nio.channels.FileLock; //导入依赖的package包/类
public synchronized int incrementNextTaskId() {
	int toRet = -1;
	try {
		FileLock l = channel.lock();
		buffer.position(0);
		int current = buffer.getInt();
		buffer.position(0);
		current++;
		toRet = current;
		buffer.putInt(current);
		l.release();
	} catch (IOException e) {
		System.err.println("SharedSystemData, IOException : " + e.getMessage());
		e.printStackTrace();
	}
	
	return toRet;
}
 
开发者ID:bizzard4,项目名称:MpiTaskFramework,代码行数:19,代码来源:SharedSystemData.java

示例3: zipFile

import java.nio.channels.FileLock; //导入依赖的package包/类
/**
 * Compactar uma arquivo.
 * @param inputFile informar o arquivo a ser compactado.
 * @param zipFilePath informar o nome e caminho zip.
 * @param iZipFile se necessário, informar uma {@link IZipFile}.
 * @throws IOException
 */
public static void zipFile(File inputFile, String zipFilePath, IZipFile iZipFile) throws IOException {
    FileOutputStream fileOutputStream = new FileOutputStream(zipFilePath);
    ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
    ZipEntry zipEntry = new ZipEntry(inputFile.getName());
    zipOutputStream.putNextEntry(zipEntry);
    FileInputStream fileInputStream = new FileInputStream(inputFile);
    FileChannel fileChannel = fileInputStream.getChannel();
    FileLock fileLock = fileChannel.tryLock(0L, Long.MAX_VALUE, /*shared*/true);
    long sizeToZip = fileInputStream.available();
    long sizeCompacted = 0;
    try {
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = fileInputStream.read(buf)) > 0) {
            sizeCompacted += bytesRead;
            zipOutputStream.write(buf, 0, bytesRead);
            if (iZipFile != null) iZipFile.progress(sizeToZip, sizeCompacted);
        }
    } finally {
        fileLock.release();
        zipOutputStream.closeEntry();
        zipOutputStream.close();
        fileOutputStream.close();
    }
}
 
开发者ID:brolam,项目名称:OpenHomeAnalysis,代码行数:33,代码来源:OhaHelper.java

示例4: testOperationActions

import java.nio.channels.FileLock; //导入依赖的package包/类
public void testOperationActions() throws Exception { // #72397
    final NbModuleProject project = generateStandaloneModule("module");
    cgpi.setProject(project);
    DialogDisplayerImpl dd = (DialogDisplayerImpl) Lookup.getDefault().lookup(DialogDisplayer.class);
    FileObject lock = FileUtil.createData(project.getProjectDirectory(), "build/testuserdir/lock");
    RandomAccessFile raf = new RandomAccessFile(FileUtil.toFile(lock), "rw");
    FileLock lck = raf.getChannel().lock();
    EventQueue.invokeAndWait(new Runnable() {
        @Override public void run() {
            ((ContextAwareAction) CommonProjectActions.deleteProjectAction()).createContextAwareInstance(Lookups.singleton(project)).actionPerformed(null);
        }
    });
    assertNotNull("warning message emitted", dd.getLastNotifyDescriptor());
    assertEquals("warning message emitted", dd.getLastNotifyDescriptor().getMessage(),
            Bundle.ERR_ModuleIsBeingRun());
    dd.reset();
    lck.release();
    raf.close();
    lock.delete();
    EventQueue.invokeAndWait(new Runnable() {
        @Override public void run() {
            CommonProjectActions.deleteProjectAction().actionPerformed(null);
        }
    });
    assertNull("no warning message", dd.getLastNotifyDescriptor());
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:27,代码来源:ModuleOperationsTest.java

示例5: writeFromSocketChannel

import java.nio.channels.FileLock; //导入依赖的package包/类
/**
	 * Will modify length of section if differnt amoutn actually written
	 * @param writeSection
	 * @param sourceChannel
	 * @throws IOException
	 */
	private void writeFromSocketChannel(Section writeSection, SocketChannel sourceChannel) throws IOException{
			synchronized (sourceChannel) {
				try (
						FileLock sectionLock = pieceChannel.lock(Integer.toUnsignedLong(writeSection.begin), Integer.toUnsignedLong(writeSection.length), false)
					)
					{
//					System.out.println("dksahfksjadh");
						int plz = writeSection.length;
						//writeSection.length = Math.toIntExact(pieceChannel.transferFrom(sourceChannel, Integer.toUnsignedLong(writeSection.begin), Integer.toUnsignedLong(writeSection.length)));
						ByteBuffer cant = ByteBuffer.allocate(plz);
						cant.clear();
						sourceChannel.read(cant);
						cant.rewind();
						pieceChannel.write(cant, writeSection.begin);
						
						
//						System.out.println("LENGTH ACTUALLY:  " + plz);

					};
			}
		
			
	}
 
开发者ID:jc0541,项目名称:URTorrent,代码行数:30,代码来源:PeerWirePiece.java

示例6: unlockFile

import java.nio.channels.FileLock; //导入依赖的package包/类
/**
 * Unlock file already locked with {@link #lockFile(String) lockFile()} method
 *
 * @param fileName file name
 */
@Override
public void unlockFile(
                        String fileName ) {

    synchronized (lockedFiles) {

        FileLock fileLock = lockedFiles.get(fileName);
        if (fileLock != null) {
            try {
                fileLock.release();
            } catch (Exception e) {
                throw new FileSystemOperationException("Could not unlock file '" + fileName + "'", e);
            } finally {
                IoUtils.closeStream(fileLock.channel());
                lockedFiles.remove(fileName);
            }
        } else {
            log.warn("File '" + fileName + "' is not locked, so we will not try to unlock it");
        }
    }
}
 
开发者ID:Axway,项目名称:ats-framework,代码行数:27,代码来源:LocalFileSystemOperations.java

示例7: tryLock

import java.nio.channels.FileLock; //导入依赖的package包/类
/**
 * Attempts to acquire an exclusive lock on the directory.
 *
 * @return A lock object representing the newly-acquired lock or
 * <code>null</code> if directory is already locked.
 * @throws IOException if locking fails.
 */
@SuppressWarnings("resource")
private FileLock tryLock(File dir) throws IOException {
  File lockF = new File(dir, FILE_LOCK);
  lockF.deleteOnExit();
  RandomAccessFile file = new RandomAccessFile(lockF, "rws");
  FileLock res = null;
  try {
    res = file.getChannel().tryLock();
  } catch (OverlappingFileLockException oe) {
    file.close();
    return null;
  } catch (IOException e) {
    LOGGER.error("Cannot create lock on " + lockF, e);
    file.close();
    throw e;
  }
  return res;
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:26,代码来源:Log.java

示例8: unzipFile

import java.nio.channels.FileLock; //导入依赖的package包/类
private File unzipFile(File cachedFile) throws IOException {
  String filename = cachedFile.getName();
  File destDir = new File(cachedFile.getParentFile(), filename + "_unzip");
  if (!destDir.exists()) {
    File lockFile = new File(cachedFile.getParentFile(), filename + "_unzip.lock");
    FileOutputStream out = new FileOutputStream(lockFile);
    try {
      FileLock lock = out.getChannel().lock();
      try {
        // Recheck in case of concurrent processes
        if (!destDir.exists()) {
          Path tempDir = fileCache.createTempDir();
          ZipUtils.unzip(cachedFile, tempDir.toFile(), newLibFilter());
          FileUtils.moveDirectory(tempDir.toFile(), destDir);
        }
      } finally {
        lock.release();
      }
    } finally {
      out.close();
      FileUtils.deleteQuietly(lockFile);
    }
  }
  return destDir;
}
 
开发者ID:instalint-org,项目名称:instalint,代码行数:26,代码来源:DefaultPluginJarExploder.java

示例9: tryWriteLock

import java.nio.channels.FileLock; //导入依赖的package包/类
/**
 * Tries to obtain a write lock on the file. This can be used to verify that no other processes concurrently
 * writes to the file, for example to check that writing to a file, i.e. on a MODIFY_ENTRY event, is completed
 * @param path
 *  the path to the file
 * @return
 *  true, if the lock could be obtained. False, if not. Please not that the lock is released once the method
 *  returns!
 */
public static boolean tryWriteLock(final Path path) {
    try(FileChannel ch = FileChannel.open(path, StandardOpenOption.WRITE);
        FileLock lock = ch.lock()){

        if(lock == null) {
            LOG.log(Level.INFO, "Could not obtain lock on file, maybe still writing");
            return false;
        } else {
            return true;
        }
    } catch (IOException e) {
        LOG.log(Level.INFO, "File not open for write access", e);
        return false;
    }
}
 
开发者ID:gmuecke,项目名称:boutique-de-jus,代码行数:25,代码来源:FileWatcher.java

示例10: fileLock

import java.nio.channels.FileLock; //导入依赖的package包/类
/** write lock file to prevent duplicate execution */
@SuppressWarnings("resource")
public static void fileLock() throws FileNotFoundException {
	lockFile = new File(Main.LOCK_FILE_LOCATION);

	FileChannel channel;
	channel = new RandomAccessFile(lockFile, "rw").getChannel();

	// try lock
	FileLock lock;
	try {
		lock = channel.tryLock();
		// already obtain lock in other JVM
		if (lock == null) {
			channel.close();
			System.exit(0);
		}
	} catch (IOException e) {
		// error handle
	}
}
 
开发者ID:Team-Sprout,项目名称:Clipcon-Client,代码行数:22,代码来源:Main.java

示例11: releaseLock

import java.nio.channels.FileLock; //导入依赖的package包/类
void releaseLock(final FileLock fileLock, final File lockFile) throws IOException {
  if (lockFile == null) {
    return;
  }

  try {
    if (fileLock != null) {
      fileLock.release();
      fileLock.channel().close();
    }
  } finally {
    if (!lockFile.delete()) {
      lockFile.deleteOnExit();
    }
  }
}
 
开发者ID:ampool,项目名称:monarch,代码行数:17,代码来源:JarDeployerDUnitTest.java

示例12: ShareFileLockHelper

import java.nio.channels.FileLock; //导入依赖的package包/类
private ShareFileLockHelper(File lockFile) throws IOException {
    this.outputStream = new FileOutputStream(lockFile);
    int numAttempts = 0;
    FileLock localFileLock = null;
    Exception saveException = null;
    while (numAttempts < 3) {
        numAttempts++;
        try {
            localFileLock = this.outputStream.getChannel().lock();
            if (localFileLock != null) {
                break;
            }
            Thread.sleep(10);
        } catch (Exception e) {
            saveException = e;
            Log.e(TAG, "getInfoLock Thread failed time:10");
        }
    }
    if (localFileLock == null) {
        throw new IOException("Tinker Exception:FileLockHelper lock file failed: " + lockFile
                .getAbsolutePath(), saveException);
    }
    this.fileLock = localFileLock;
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:25,代码来源:ShareFileLockHelper.java

示例13: isPreUpgradableLayout

import java.nio.channels.FileLock; //导入依赖的package包/类
@Override
public boolean isPreUpgradableLayout(StorageDirectory sd) throws IOException {
  File oldF = new File(sd.getRoot(), "storage");
  if (!oldF.exists())
    return false;
  // check the layout version inside the storage file
  // Lock and Read old storage file
  RandomAccessFile oldFile = new RandomAccessFile(oldF, "rws");
  FileLock oldLock = oldFile.getChannel().tryLock();
  try {
    oldFile.seek(0);
    int oldVersion = oldFile.readInt();
    if (oldVersion < LAST_PRE_UPGRADE_LAYOUT_VERSION)
      return false;
  } finally {
    oldLock.release();
    oldFile.close();
  }
  return true;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:21,代码来源:DataStorage.java

示例14: lock

import java.nio.channels.FileLock; //导入依赖的package包/类
/**
 * Lock storage to provide exclusive access.
 * 
 * <p> Locking is not supported by all file systems.
 * E.g., NFS does not consistently support exclusive locks.
 * 
 * <p> If locking is supported we guarantee exclusive access to the
 * storage directory. Otherwise, no guarantee is given.
 * 
 * @throws IOException if locking fails
 */
public void lock() throws IOException {
  if (isShared()) {
    LOG.info("Locking is disabled for " + this.root);
    return;
  }
  FileLock newLock = tryLock();
  if (newLock == null) {
    String msg = "Cannot lock storage " + this.root 
      + ". The directory is already locked";
    LOG.info(msg);
    throw new IOException(msg);
  }
  // Don't overwrite lock until success - this way if we accidentally
  // call lock twice, the internal state won't be cleared by the second
  // (failed) lock attempt
  lock = newLock;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:29,代码来源:Storage.java

示例15: isLockSupported

import java.nio.channels.FileLock; //导入依赖的package包/类
/**
 * Check whether underlying file system supports file locking.
 * 
 * @return <code>true</code> if exclusive locks are supported or
 *         <code>false</code> otherwise.
 * @throws IOException
 * @see StorageDirectory#lock()
 */
public boolean isLockSupported() throws IOException {
  FileLock firstLock = null;
  FileLock secondLock = null;
  try {
    firstLock = lock;
    if(firstLock == null) {
      firstLock = tryLock();
      if(firstLock == null)
        return true;
    }
    secondLock = tryLock();
    if(secondLock == null)
      return true;
  } finally {
    if(firstLock != null && firstLock != lock) {
      firstLock.release();
      firstLock.channel().close();
    }
    if(secondLock != null) {
      secondLock.release();
      secondLock.channel().close();
    }
  }
  return false;
}
 
开发者ID:naver,项目名称:hadoop,代码行数:34,代码来源:Storage.java


注:本文中的java.nio.channels.FileLock类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。