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


Java FileChannel.tryLock方法代码示例

本文整理汇总了Java中java.nio.channels.FileChannel.tryLock方法的典型用法代码示例。如果您正苦于以下问题:Java FileChannel.tryLock方法的具体用法?Java FileChannel.tryLock怎么用?Java FileChannel.tryLock使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.nio.channels.FileChannel的用法示例。


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

示例1: zipFile

import java.nio.channels.FileChannel; //导入方法依赖的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

示例2: fileLock

import java.nio.channels.FileChannel; //导入方法依赖的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

示例3: getFileLock

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
public boolean getFileLock() {

        boolean result = true;
        try {
            FileChannel fc = FileChannel.open(this.filePath, StandardOpenOption.READ, StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE);
            fileLock = fc.tryLock();

            if (fileLock == null) {
                result = false;
            }
        }
        catch (Exception ex) {
            result = false;
        }

        return result;
    }
 
开发者ID:uavorg,项目名称:uavstack,代码行数:19,代码来源:UpgradeProcessLock.java

示例4: getFileLockForWriting

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Get file lock for writing too file
 * <p/>
 * TODO:this appears to have little effect on Windows Vista
 *
 * @param fileChannel
 * @param filePath
 * @return lock or null if locking is not supported
 * @throws IOException                                    if unable to get lock because already locked by another program
 * @throws java.nio.channels.OverlappingFileLockException if already locked by another thread in the same VM, we dont catch this
 *                                                        because indicates a programming error
 */
protected FileLock getFileLockForWriting(FileChannel fileChannel, String filePath) throws IOException {
    logger.finest("locking fileChannel for " + filePath);
    FileLock fileLock;
    try {
        fileLock = fileChannel.tryLock();
    }
    //Assumes locking is not supported on this platform so just returns null
    catch (IOException exception) {
        return null;
    }

    //Couldnt getFields lock because file is already locked by another application
    if (fileLock == null) {
        throw new IOException(ErrorMessage.GENERAL_WRITE_FAILED_FILE_LOCKED.getMsg(filePath));
    }
    return fileLock;
}
 
开发者ID:openaudible,项目名称:openaudible,代码行数:30,代码来源:AbstractID3v2Tag.java

示例5: tryLockInternal

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private static ProcessLock tryLockInternal(final String lockName, final String hash, final boolean writeMode) {
    synchronized (LOCK_MAP) {

        ConcurrentHashMap<Integer, ProcessLock> locks = LOCK_MAP.get(lockName);
        if (locks != null && !locks.isEmpty()) {
            Iterator<Map.Entry<Integer, ProcessLock>> itr = locks.entrySet().iterator();
            while (itr.hasNext()) {
                Map.Entry<Integer, ProcessLock> entry = itr.next();
                ProcessLock value = entry.getValue();
                if (value != null) {
                    if (!value.isValid()) {
                        itr.remove();
                    } else if (writeMode) {
                        return null;
                    } else if (value.mWriteMode) {
                        return null;
                    }
                } else {
                    itr.remove();
                }
            }
        }

        FileChannel channel = null;
        Closeable stream = null;
        try {
            File file = new File(
                    x.app().getDir(LOCK_FILE_DIR, Context.MODE_PRIVATE),
                    hash);
            if (file.exists() || file.createNewFile()) {

                if (writeMode) {
                    FileOutputStream out = new FileOutputStream(file, false);
                    channel = out.getChannel();
                    stream = out;
                } else {
                    FileInputStream in = new FileInputStream(file);
                    channel = in.getChannel();
                    stream = in;
                }
                if (channel != null) {
                    FileLock fileLock = channel.tryLock(0L, Long.MAX_VALUE, !writeMode);
                    if (isValid(fileLock)) {
                        ProcessLock result = new ProcessLock(lockName, file, fileLock, stream, writeMode);
                        LOCK_MAP.put(lockName, fileLock.hashCode(), result);
                        return result;
                    } else {
                        release(lockName, fileLock, file, stream);
                    }
                } else {
                    throw new IOException("can not get file channel:" + file.getAbsolutePath());
                }
            }
        } catch (Throwable ignored) {
            LogUtil.d("tryLock: " + lockName + ", " + ignored.getMessage());
            IOUtil.closeQuietly(stream);
            IOUtil.closeQuietly(channel);
        }
    }

    return null;
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:63,代码来源:ProcessLock.java

示例6: obtainLock

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@Override
public Lock obtainLock(@NonNull Directory dir, String lockName) throws IOException {
    if (!(dir instanceof RedisDirectory)) {
        throw new IllegalArgumentException("Expect argument of type [" + RedisDirectory.class.getName() + "]!");
    }
    Path lockFile = lockFileDirectory.resolve(lockName);
    try {
        Files.createFile(lockFile);
        log.debug("Lock file path = {}", lockFile.toFile().getAbsolutePath());
    } catch (IOException ignore) {
        //ignore
        log.debug("Lock file already exists!");
    }
    final Path realPath = lockFile.toRealPath();
    final FileTime creationTime = Files.readAttributes(realPath, BasicFileAttributes.class).creationTime();
    if (LOCK_HELD.add(realPath.toString())) {
        FileChannel fileChannel = null;
        FileLock lock = null;
        try {
            fileChannel = FileChannel.open(realPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
            lock = fileChannel.tryLock();
            if (lock != null) {
                return new RedisLock(lock, fileChannel, realPath, creationTime);
            } else {
                throw new LockObtainFailedException("Lock held by another program: " + realPath);
            }
        } finally {
            if (lock == null) {
                IOUtils.closeQuietly(fileChannel);
                clearLockHeld(realPath);
            }
        }
    } else {
        throw new LockObtainFailedException("Lock held by this virtual machine: " + realPath);
    }
}
 
开发者ID:shijiebei2009,项目名称:RedisDirectory,代码行数:37,代码来源:RedisLockFactory.java

示例7: getLock

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
@SuppressWarnings("resource")
public static synchronized FileLock getLock(File file)
{
	System.out.println("Attempting to acquire file lock for " + file.getAbsolutePath());
	FileChannel channel = null;
	try
	{
		channel = new RandomAccessFile(file, "rw").getChannel();
		return channel.tryLock();
	}
	catch (IOException | OverlappingFileLockException e)
	{
		System.err.println("Failed to lock channel");
		e.printStackTrace();

		if (channel != null)
		{
			try
			{
				channel.close();
			}
			catch (IOException e1)
			{
				System.err.println("Failed to close lock channel");
				e1.printStackTrace();
			}
		}
		return null;
	}
}
 
开发者ID:PolyphasicDevTeam,项目名称:NoMoreOversleeps,代码行数:31,代码来源:LockingHelper.java

示例8: getFileLockForWriting

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Get file lock for writing too file
 * <p/>
 * TODO:this appears to have little effect on Windows Vista
 *
 * @param fileChannel
 * @param filePath
 * @return lock or null if locking is not supported
 * @throws IOException                                    if unable to get lock because already locked by another program
 * @throws java.nio.channels.OverlappingFileLockException if already locked by another thread in the same VM, we dont catch this
 *                                                        because indicates a programming error
 */
protected FileLock getFileLockForWriting(FileChannel fileChannel, String filePath) throws IOException
{
    logger.finest("locking fileChannel for " + filePath);
    FileLock fileLock;
    try
    {
        fileLock = fileChannel.tryLock();
    }
    //Assumes locking is not supported on this platform so just returns null
    catch (IOException exception)
    {
        return null;
    }
    //#129 Workaround for https://bugs.openjdk.java.net/browse/JDK-8025619
    catch (Error error)
    {
        return null;
    }

    //Couldnt getFields lock because file is already locked by another application
    if (fileLock == null)
    {
        throw new IOException(ErrorMessage.GENERAL_WRITE_FAILED_FILE_LOCKED.getMsg(filePath));
    }
    return fileLock;
}
 
开发者ID:GlennioTech,项目名称:MetadataEditor,代码行数:39,代码来源:AbstractID3v2Tag.java

示例9: tryAcquireLock

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
private FileLock tryAcquireLock(final FileChannel channel) throws IOException {
    try {
        return channel.tryLock();
    } catch (OverlappingFileLockException e) {
        return null;
    }
}
 
开发者ID:YMCoding,项目名称:kafka-0.11.0.0-src-with-comment,代码行数:8,代码来源:StateDirectory.java

示例10: setup

import java.nio.channels.FileChannel; //导入方法依赖的package包/类
/**
 * Setup all the files and directories needed for the tests
 *
 * @return writable directory created that needs to be deleted when done
 * @throws RuntimeException
 */
private static File setup() throws RuntimeException {
    // First do some setup in the temporary directory (using same logic as
    // FileHandler for %t pattern)
    String tmpDir = System.getProperty("java.io.tmpdir"); // i.e. %t
    if (tmpDir == null) {
        tmpDir = System.getProperty("user.home");
    }
    File tmpOrHomeDir = new File(tmpDir);
    // Create a writable directory here (%t/writable-lockfile-dir)
    File writableDir = new File(tmpOrHomeDir, WRITABLE_DIR);
    if (!createFile(writableDir, true)) {
        throw new RuntimeException("Test setup failed: unable to create"
                + " writable working directory "
                + writableDir.getAbsolutePath() );
    }

    // try to determine whether file locking is supported
    final String uniqueFileName = UUID.randomUUID().toString()+".lck";
    try {
        FileChannel fc = FileChannel.open(Paths.get(writableDir.getAbsolutePath(),
                uniqueFileName),
                StandardOpenOption.CREATE_NEW, StandardOpenOption.APPEND,
                StandardOpenOption.DELETE_ON_CLOSE);
        try {
            fc.tryLock();
        } catch(IOException x) {
            supportsLocking = false;
        } finally {
            fc.close();
        }
    } catch (IOException t) {
        // should not happen
        System.err.println("Failed to create new file " + uniqueFileName +
                " in " + writableDir.getAbsolutePath());
        throw new RuntimeException("Test setup failed: unable to run test", t);
    }
    return writableDir;
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:45,代码来源:CheckZombieLockTest.java


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