List of usage examples for java.nio.channels FileChannel lock
public final FileLock lock() throws IOException
From source file:org.geoserver.rest.util.IOUtils.java
/** * Optimize version of copy method for file channels. * //from ww w . j a v a2 s . c om * @param bufferSize size of the temp buffer to use for this copy. * @param source the source {@link ReadableByteChannel}. * @param destination the destination {@link WritableByteChannel};. * @throws IOException in case something bad happens. */ public static void copyFileChannel(int bufferSize, FileChannel source, FileChannel destination) throws IOException { inputNotNull(source, destination); if (!source.isOpen() || !destination.isOpen()) throw new IllegalStateException("Source and destination channels must be open."); FileLock lock = null; try { lock = destination.lock(); final long sourceSize = source.size(); long pos = 0; while (pos < sourceSize) { // read and flip final long remaining = (sourceSize - pos); final int mappedZoneSize = remaining >= bufferSize ? bufferSize : (int) remaining; destination.transferFrom(source, pos, mappedZoneSize); // update zone pos += mappedZoneSize; } } finally { if (lock != null) { try { lock.release(); } catch (Throwable t) { if (LOGGER.isLoggable(Level.INFO)) LOGGER.log(Level.INFO, t.getLocalizedMessage(), t); } } } }
From source file:com.sqlite.multiread.java
public void run() { newSqLiteAdapter.openToRead();// www. ja va2 s .com long seconds1 = 0; long seconds2 = 0; Cursor cur = null; Transactions transactions = new Transactions(); ArrayList<Long> array = new ArrayList<Long>(); for (int i = 0; i < 10; i++) { seconds1 = System.currentTimeMillis(); //cur = newSqLiteAdapter.queueAll("dammyTable", false, false, false, // false, false, false, true, threadNum); seconds2 = System.currentTimeMillis(); array.add(seconds2 - seconds1); } // newSqLiteAdapter.close(); FileOutputStream fos = null; try { byte[] data = new String("\nTotal time: " + transactions.average_time(array) / 8 + "ms Thread Id: " + currentThread().getId() + " I Have read " + cur.getCount()).getBytes(); File file = new File(Environment.getExternalStorageDirectory() + "/Aaa/", "threadsResults.txt"); FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); FileLock lock = channel.lock(); try { lock = channel.tryLock(); } catch (OverlappingFileLockException e) { } fos = new FileOutputStream(file, true); fos.write(data); fos.flush(); lock.release(); channel.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.forgerock.openidm.script.javascript.JavaScriptFactory.java
private Script initializeScript(String name, String source, boolean sharedScope) throws ScriptException { initDebugListener();/*from w ww . j a va 2 s . com*/ if (debugInitialised) { try { FileChannel outChannel = new FileOutputStream(getTargetFile(name)).getChannel(); FileLock outLock = outChannel.lock(); ByteBuffer buf = ByteBuffer.allocate(source.length()); buf.put(source.getBytes("UTF-8")); buf.flip(); outChannel.write(buf); outLock.release(); outChannel.close(); } catch (IOException e) { logger.warn("JavaScript source was not updated for {}", name, e); } } return new JavaScript(name, source, sharedScope); }
From source file:org.forgerock.openidm.script.javascript.JavaScriptFactory.java
private Script initializeScript(String name, File source, boolean sharedScope) throws ScriptException { initDebugListener();/*ww w. j ava2 s. c om*/ if (debugInitialised) { try { FileChannel inChannel = new FileInputStream(source).getChannel(); FileChannel outChannel = new FileOutputStream(getTargetFile(name)).getChannel(); FileLock outLock = outChannel.lock(); FileLock inLock = inChannel.lock(0, inChannel.size(), true); inChannel.transferTo(0, inChannel.size(), outChannel); outLock.release(); inLock.release(); inChannel.close(); outChannel.close(); } catch (IOException e) { logger.warn("JavaScript source was not updated for {}", name, e); } } return new JavaScript(name, source, sharedScope); }
From source file:com.ephesoft.dcma.util.FileUtils.java
/** * API to take read write lock on the folder represented by the given folder path. * /*from w w w . ja va 2 s .com*/ * @param folderPath {@link String} * @return true if lock is successfully acquired, else false */ public static boolean lockFolder(String folderPath) { String lockFileName = folderPath + File.separator + "_lock"; boolean isLockAcquired = true; try { File lockFile = new File(lockFileName); FileChannel fileChannel = new RandomAccessFile(lockFile, "rw").getChannel(); FileLock lock = fileChannel.lock(); try { if (lock == null) { lock = fileChannel.tryLock(); } } catch (OverlappingFileLockException e) { LOGGER.trace("File is already locked in this thread or virtual machine"); } if (lock == null) { LOGGER.trace("File is already locked in this thread or virtual machine"); } } catch (Exception e) { LOGGER.error("Unable to aquire lock on file : " + lockFileName, e); isLockAcquired = false; } return isLockAcquired; }
From source file:com.thoughtworks.go.config.GoConfigFileWriter.java
public synchronized void writeToConfigXmlFile(String content) { FileChannel channel = null; FileOutputStream outputStream = null; FileLock lock = null;//from w ww . j a va 2s.com try { RandomAccessFile randomAccessFile = new RandomAccessFile(fileLocation(), "rw"); channel = randomAccessFile.getChannel(); lock = channel.lock(); randomAccessFile.seek(0); randomAccessFile.setLength(0); outputStream = new FileOutputStream(randomAccessFile.getFD()); IOUtils.write(content, outputStream, UTF_8); } catch (Exception e) { throw new RuntimeException(e); } finally { if (channel != null && lock != null) { try { lock.release(); channel.close(); IOUtils.closeQuietly(outputStream); } catch (IOException e) { LOGGER.error("Error occured when releasing file lock and closing file.", e); } } } }
From source file:com.emc.vipr.sync.source.FilesystemSource.java
protected void delete(File file) { // Try to lock the file first. If this fails, the file is // probably open for write somewhere. // Note that on a mac, you can apparently delete files that // someone else has open for writing, and can lock files // too./*from w w w .j a va 2 s .co m*/ // Must make sure to throw exceptions when necessary to flag actual failures as opposed to skipped files. if (file.isDirectory()) { File metaDir = getMetaFile(file).getParentFile(); if (metaDir.exists()) metaDir.delete(); // Just try and delete dir if (!file.delete()) { LogMF.warn(l4j, "Failed to delete directory {0}", file); } } else { boolean tryDelete = true; if (deleteOlderThan > 0) { if (System.currentTimeMillis() - file.lastModified() < deleteOlderThan) { LogMF.info(l4j, "not deleting {0}; it is not at least {1} ms old", file, deleteOlderThan); tryDelete = false; } } if (deleteCheckScript != null) { String[] args = new String[] { deleteCheckScript.getAbsolutePath(), file.getAbsolutePath() }; try { l4j.debug("delete check: " + Arrays.asList(args)); Process p = Runtime.getRuntime().exec(args); while (true) { try { int exitCode = p.exitValue(); if (exitCode == 0) { LogMF.debug(l4j, "delete check OK, exit code {0}", exitCode); } else { LogMF.info(l4j, "delete check failed, exit code {0}. Not deleting file.", exitCode); tryDelete = false; } break; } catch (IllegalThreadStateException e) { // Ignore. } } } catch (IOException e) { LogMF.info(l4j, "error executing delete check script: {0}. Not deleting file.", e.toString()); tryDelete = false; } } RandomAccessFile raf = null; if (tryDelete) { try { raf = new RandomAccessFile(file, "rw"); FileChannel fc = raf.getChannel(); FileLock flock = fc.lock(); // If we got here, we should be good. flock.release(); if (!file.delete()) { throw new RuntimeException(MessageFormat.format("Failed to delete {0}", file)); } } catch (IOException e) { throw new RuntimeException(MessageFormat .format("File {0} not deleted, it appears to be open: {1}", file, e.getMessage())); } finally { if (raf != null) { try { raf.close(); } catch (IOException e) { // Ignore. } } } } } }
From source file:de.ailis.oneinstance.OneInstance.java
/** * Locks the specified lock file./*from w w w.j a va 2s .c o m*/ * * @param lockFile * The lock file. * @return The lock or null if no locking could be performed. */ private FileLock lock(final File lockFile) { try { FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel(); return channel.lock(); } catch (IOException e) { LOG.warn("Unable to lock the lock file: " + e + ". Trying to run without a lock.", e); return null; } }
From source file:no.sesat.search.http.filters.SiteJspLoaderFilter.java
private void downloadJsp(final HttpServletRequest request, final String jsp) throws MalformedURLException { final StopWatch stopWatch = new StopWatch(); stopWatch.start();/*w ww.j a v a2 s. c om*/ byte[] golden = new byte[0]; // search skins for the jsp and write it out to "golden" for (Site site = (Site) request.getAttribute(Site.NAME_KEY); 0 == golden.length; site = site.getParent()) { if (null == site) { if (null == config.getServletContext().getResource(jsp)) { throw new ResourceLoadException("Unable to find " + jsp + " in any skin"); } break; } final Site finalSite = site; final BytecodeLoader bcLoader = UrlResourceLoader.newBytecodeLoader(finalSite.getSiteContext(), jsp, null); bcLoader.abut(); golden = bcLoader.getBytecode(); } // if golden now contains data save it to a local (ie local web application) file if (0 < golden.length) { try { final File file = new File(root + jsp); // create the directory structure file.getParentFile().mkdirs(); // check existing file boolean needsUpdating = true; final boolean fileExisted = file.exists(); if (!fileExisted) { file.createNewFile(); } // channel.lock() only synchronises file access between programs, but not between threads inside // the current JVM. The latter results in the OverlappingFileLockException. // At least this is my current understanding of java.nio.channels // It may be that no synchronisation or locking is required at all. A beer to whom answers :-) // So we must provide synchronisation between our own threads, // synchronisation against the file's path (using the JVM's String.intern() functionality) // should work. (I can't imagine this string be used for any other synchronisation purposes). synchronized (file.toString().intern()) { RandomAccessFile fileAccess = null; FileChannel channel = null; try { fileAccess = new RandomAccessFile(file, "rws"); channel = fileAccess.getChannel(); channel.lock(); if (fileExisted) { final byte[] bytes = new byte[(int) channel.size()]; final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); int reads; do { reads = channel.read(byteBuffer); } while (0 < reads); needsUpdating = !Arrays.equals(golden, bytes); } if (needsUpdating) { // download file from skin channel.write(ByteBuffer.wrap(golden), 0); file.deleteOnExit(); } } finally { if (null != channel) { channel.close(); } if (null != fileAccess) { fileAccess.close(); } LOG.debug("resource created as " + config.getServletContext().getResource(jsp)); } } } catch (IOException ex) { LOG.error(ex.getMessage(), ex); } } stopWatch.stop(); LOG.trace("SiteJspLoaderFilter.downloadJsp(..) took " + stopWatch); }
From source file:org.apache.htrace.impl.HTracedSpanReceiver.java
void appendToDroppedSpansLog(String text) throws IOException { // Is the dropped spans log is disabled? if (conf.droppedSpansLogPath.isEmpty() || (conf.droppedSpansLogMaxSize == 0)) { return;/*from w w w . j a v a 2 s . com*/ } FileLock lock = null; String msg = ISO_DATE_FORMAT.format(new Date()) + ": " + text; ByteBuffer bb = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8)); // FileChannel locking corresponds to advisory locking on UNIX. It will // protect multiple processes from attempting to write to the same dropped // spans log at once. However, within a single process, we need this // synchronized block to ensure that multiple HTracedSpanReceiver objects // don't try to write to the same log at once. (It is unusal to configure // multiple HTracedSpanReceiver objects, but possible.) synchronized (HTracedSpanReceiver.class) { FileChannel channel = FileChannel.open(Paths.get(conf.droppedSpansLogPath), APPEND, CREATE, WRITE); try { lock = channel.lock(); long size = channel.size(); if (size > conf.droppedSpansLogMaxSize) { throw new IOException("Dropped spans log " + conf.droppedSpansLogPath + " is already " + size + " bytes; will not add to it."); } else if ((size == 0) && (DROPPED_SPANS_FILE_PERMS != null)) { // Set the permissions of the dropped spans file so that other // processes can write to it. Files.setPosixFilePermissions(Paths.get(conf.droppedSpansLogPath), DROPPED_SPANS_FILE_PERMS); } channel.write(bb); } finally { try { if (lock != null) { lock.release(); } } finally { channel.close(); } } } }