List of usage examples for java.nio.channels FileLock release
public abstract void release() throws IOException;
From source file:com.asakusafw.runtime.util.lock.LocalFileLockProvider.java
@Override public LocalFileLockObject<T> tryLock(T target) throws IOException { if (baseDirectory.mkdirs() == false && baseDirectory.isDirectory() == false) { throw new IOException(MessageFormat.format("Failed to create lock directory: {0}", baseDirectory)); }//from w ww. j a v a2 s . co m String fileName = String.format("%08x.lck", target == null ? -1 : target.hashCode()); //$NON-NLS-1$ File lockFile = new File(baseDirectory, fileName); RandomAccessFile fd = new RandomAccessFile(lockFile, "rw"); //$NON-NLS-1$ boolean success = false; try { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format("Start to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$ target, lockFile)); } FileLock lockEntity = getLock(target, lockFile, fd); if (lockEntity == null) { return null; } else { if (LOG.isDebugEnabled()) { LOG.debug(MessageFormat.format("Finished to acquire lock for \"{0}\" ({1})", //$NON-NLS-1$ target, lockFile)); } try { fd.seek(0L); fd.setLength(0L); fd.write(String.valueOf(target).getBytes(ENCODING)); success = true; return new LocalFileLockObject<>(target, lockFile, fd, lockEntity); } finally { if (success == false) { lockEntity.release(); } } } } finally { if (success == false) { fd.close(); } } }
From source file:com.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * Deletes a newsdrilldown from the db.//from w w w . j a v a2s . c o m * * @param entity The newsdrilldown to delete */ public void delete(UXBEntity entity) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); Query query = em.createQuery(new StringBuilder() .append("FROM news x WHERE x.fs_id = :fs_id AND x.language = :language").toString()); query.setParameter("fs_id", Long.parseLong(entity.getUuid())); query.setParameter("language", entity.getLanguage()); if (!query.getResultList().isEmpty()) { News art = (News) query.getSingleResult(); // delete file from filesystem URL url = new URL(art.getUrl()); File file = new File(webpath + url.getPath()); if (file.exists()) { // Try acquiring the lock without blocking. This method returns // null or throws an exception if the file is already locked. try { FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); // Try to lock the file FileLock lock = channel.tryLock(); // Delete the file file.delete(); // Release the lock lock.release(); lock.channel().close(); } catch (OverlappingFileLockException e) { logger.info("File is already locked in this thread or virtual machine"); } catch (MalformedURLException e) { logger.info("wrong url", e); } } // remove article from content repository em.remove(art); } tx.commit(); } catch (Exception e) { if (tx != null) { tx.setRollbackOnly(); } throw e; } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }
From source file:ca.uviccscu.lp.server.main.ShutdownListener.java
@Deprecated public void releaseLocks() { l.trace("Trying to check file locks "); try {// w ww .j a v a 2s . c om Collection c = FileUtils.listFiles(new File(Shared.workingDirectory), null, true); Object[] arr = c.toArray(); for (int i = 0; i < arr.length; i++) { l.trace("Trying lock for: " + ((File) arr[i]).getAbsolutePath()); // Get a file channel for the file File file = ((File) arr[i]); FileChannel channel = new RandomAccessFile(file, "rw").getChannel(); // Use the file channel to create a lock on the file. // This method blocks until it can retrieve the lock. //FileLock lock = channel.lock(); // Try acquiring the lock without blocking. This method returns // null or throws an exception if the file is already locked. FileLock lock = null; try { lock = channel.lock(); } catch (OverlappingFileLockException ex) { l.trace("Lock already exists", ex); } if (lock == null) { l.trace("Lock failed - someone else holds lock"); } else { l.trace("Lock shared: " + lock.isShared() + " Lock valid: " + lock.isValid()); lock.release(); l.trace("Lock release OK"); try { if (!file.delete()) { throw new IOException(); } } catch (Exception e) { l.trace("Delete failed", e); } } } //Thread.sleep(25000); } catch (Exception e) { // File is already locked in this thread or virtual machine l.trace("File lock problem", e); } }
From source file:com.linuxbox.enkive.archiver.AbstractMessageArchivingService.java
private String saveToDisk(String messageData, String fileName) throws FailedToEmergencySaveException, SaveFileAlreadyExistsException { File emergencySaveFile = null; String emergencySaveFilePath = "UNKNOWN"; BufferedWriter out = null;/*ww w .j a v a 2 s . c o m*/ FileOutputStream fileStream = null; try { emergencySaveFile = new File(getEmergencySaveRoot(), fileName); emergencySaveFilePath = emergencySaveFile.getCanonicalPath(); fileStream = new FileOutputStream(emergencySaveFile); FileLock lock = null; try { lock = fileStream.getChannel().tryLock(); if (lock == null) { throw new SaveFileAlreadyExistsException(emergencySaveFilePath); } out = new BufferedWriter(new OutputStreamWriter(fileStream)); out.write(messageData); if (LOGGER.isInfoEnabled()) { LOGGER.info("Saved message to file: \"" + emergencySaveFilePath + "\""); } return emergencySaveFilePath; } finally { if (lock != null) { lock.release(); } } } catch (IOException e) { LOGGER.fatal("Emergency save to disk failed. ", e); throw new FailedToEmergencySaveException(e); } finally { try { if (out != null) { out.close(); } else if (fileStream != null) { fileStream.close(); } } catch (IOException e) { if (LOGGER.isWarnEnabled()) { LOGGER.warn("Could not close emergency save file \"" + emergencySavePath + "\"."); } } } }
From source file:com.att.api.oauth.OAuthToken.java
/** * Attempts to load an OAuthToken from a file in an asynchronous-safe * manner./*from www . ja v a 2 s . c o m*/ * * <p> * If <code>fpath</code> does not exist or some required values are missing * from the saved file, null is returned. * </p> * * <p> * <strong>WARNING</strong>: Because caching may be used, manually modifying * the saved token properties file may yield unexpected results unless * caching is disabled. * </p> * * @param fpath file path from which to load token * @return OAuthToken an OAuthToken object if successful, null otherwise * @throws IOException if there was an error loading the token * @see #useTokenCaching(boolean) */ public static OAuthToken loadToken(String fpath) throws IOException { FileInputStream fInputStream = null; FileLock fLock = null; synchronized (LOCK_OBJECT) { // attempt to load from cached tokens, thereby saving file I/O if (cachedTokens != null && cachedTokens.get(fpath) != null) { return cachedTokens.get(fpath); } if (!new File(fpath).exists()) { return null; } try { fInputStream = new FileInputStream(fpath); // acquire shared lock fLock = fInputStream.getChannel().lock(0L, Long.MAX_VALUE, true); Properties props = new Properties(); props.load(fInputStream); if (!props.containsKey("creationTime") || !props.containsKey("expiresIn")) { return null; } String accessToken = props.getProperty("accessToken"); if (accessToken == null || accessToken.equals("")) { return null; } String refreshToken = props.getProperty("refreshToken"); String sExpiresIn = props.getProperty("expiresIn"); long expiresIn = new Long(sExpiresIn).longValue(); String sCreationTime = props.getProperty("creationTime"); long creationTime = new Long(sCreationTime).longValue(); return new OAuthToken(accessToken, expiresIn, refreshToken, creationTime); } catch (IOException e) { throw e; // pass along exception } finally { if (fLock != null) { fLock.release(); } if (fInputStream != null) { fInputStream.close(); } } } }
From source file:org.spf4j.perf.tsdb.TimeSeriesDatabase.java
public void reReadTableInfos() throws IOException { synchronized (path) { FileLock lock = ch.lock(0, Long.MAX_VALUE, true); try {// w ww . j a v a 2 s . co m toc = new TableOfContents(file, toc.getLocation()); // reread toc readTableInfos(); } catch (IOException | RuntimeException e) { try { lock.release(); throw e; } catch (IOException ex) { ex.addSuppressed(e); throw ex; } } lock.release(); } }
From source file:org.apache.axiom.attachments.impl.BufferUtils.java
/** * Opimized writing to FileOutputStream using a channel * @param is// w ww.j av a 2 s. c o m * @param fos * @return false if lock was not aquired * @throws IOException */ public static boolean inputStream2FileOutputStream(InputStream is, FileOutputStream fos) throws IOException { // See if a file channel and lock can be obtained on the FileOutputStream FileChannel channel = null; FileLock lock = null; ByteBuffer bb = null; try { channel = fos.getChannel(); if (channel != null) { lock = channel.tryLock(); } bb = getTempByteBuffer(); } catch (Throwable t) { } if (lock == null || bb == null || !bb.hasArray()) { releaseTempByteBuffer(bb); return false; // lock could not be set or bb does not have direct array access } try { // Read directly into the ByteBuffer array int bytesRead = is.read(bb.array()); // Continue reading until no bytes are read and no // bytes are now available. while (bytesRead > 0 || is.available() > 0) { if (bytesRead > 0) { int written = 0; if (bytesRead < BUFFER_LEN) { // If the ByteBuffer is not full, allocate a new one ByteBuffer temp = ByteBuffer.allocate(bytesRead); temp.put(bb.array(), 0, bytesRead); temp.position(0); written = channel.write(temp); } else { // Write to channel bb.position(0); written = channel.write(bb); bb.clear(); } } // REVIEW: Do we need to ensure that bytesWritten is // the same as the number of bytes sent ? bytesRead = is.read(bb.array()); } } finally { // Release the lock lock.release(); releaseTempByteBuffer(bb); } return true; }
From source file:org.apache.hadoop.dfs.StorageInfo.java
/** * Check whether underlying file system supports file locking. * //from w ww . ja v a2 s.com * @return <code>true</code> if exclusive locks are supported or * <code>false</code> otherwise. * @throws IOException * @see StorageDirectory#lock() */ boolean isLockSupported(int idx) throws IOException { StorageDirectory sd = storageDirs.get(idx); FileLock firstLock = null; FileLock secondLock = null; try { firstLock = sd.lock; if (firstLock == null) { firstLock = sd.tryLock(); if (firstLock == null) return true; } secondLock = sd.tryLock(); if (secondLock == null) return true; } finally { if (firstLock != null && firstLock != sd.lock) { firstLock.release(); firstLock.channel().close(); } if (secondLock != null) { secondLock.release(); secondLock.channel().close(); } } return false; }
From source file:org.fuin.utils4j.Utils4JTest.java
/** * Create a runnable that locks the file. * // w ww . j av a 2 s .c o m * @param file * File to lock. * @param ec * If an exception occurs it will stored in this object. * @param tryLockMax * Number of tries to lock before throwing an exception. * @param tryWaitMillis * Milliseconds to sleep between retries. * @param sleepMillis * Number of milliseconds to hold the lock. * * @return New runnable instance. */ private Runnable createLockRunnable(final File file, final ExceptionContainer ec, final int tryLockMax, final long tryWaitMillis, final long sleepMillis) { return new Runnable() { public void run() { try { final RandomAccessFile raf = new RandomAccessFile(file, "rw"); try { final FileLock lock = Utils4J.lockRandomAccessFile(raf, tryLockMax, tryWaitMillis); try { // Hold the lock for one second Thread.sleep(sleepMillis); } finally { lock.release(); } } finally { raf.close(); } } catch (final Exception ex) { ec.exception = ex; } } }; }
From source file:org.apache.flume.channel.file.Log.java
/** * Unlock directory.//from w ww.ja va 2 s.c om * * @throws IOException */ private void unlock(File dir) throws IOException { FileLock lock = locks.remove(dir.getAbsolutePath()); if (lock == null) { return; } lock.release(); lock.channel().close(); lock = null; }