List of usage examples for java.nio.channels FileChannel tryLock
public final FileLock tryLock() throws IOException
From source file:com.taobao.common.tfs.impl.GcWorker.java
private void doGc(SegmentInfoContainer segmentInfoContainer, File[] fileList) { for (File file : fileList) { if (file.length() == 0) { log.info("expired gc file is empty, unlink. " + file.getAbsolutePath()); file.delete();//from w ww . ja va 2 s. com continue; } String fileName = file.getAbsolutePath(); log.info("do gc filename " + fileName); int serverIdIndex = fileName.lastIndexOf('!'); if (serverIdIndex == -1) { log.error("file name is invalid, no server id: " + fileName); // unlink ? continue; } FileLock fileLock = null; try { FileChannel fileChannel = (new RandomAccessFile(file, "rw")).getChannel(); fileLock = fileChannel.tryLock(); if (fileLock == null) { log.warn("file: " + fileName + " is busy, maybe another gc worker is working over it"); continue; } long serverId = Long.parseLong(fileName.substring(serverIdIndex + 1)); segmentInfoContainer.loadFile(fileName); Collection<SegmentInfo> segmentInfos = segmentInfoContainer.getSegmentInfos(); for (SegmentInfo segmentInfo : segmentInfos) { if (tfsManager.unlinkFile(segmentInfo.getBlockId(), segmentInfo.getFileId(), serverId)) { log.info("gc success. blockId: " + segmentInfo.getBlockId() + " fileId: " + segmentInfo.getFileId() + " serverId: " + serverId); } else { log.error("gc fail. blockId: " + segmentInfo.getFileId() + " fileId: " + segmentInfo.getFileId() + " serverId: " + serverId); } } } catch (Exception e) { log.warn("", e); } finally { try { if (fileLock != null) { fileLock.release(); } segmentInfoContainer.cleanUp(); // delete anyway file.delete(); } catch (Exception e) { log.warn("filelock realse fail.", e); } } } }
From source file:com.sqlite.multiread.java
public void run() { newSqLiteAdapter.openToRead();//from ww w . j av a 2 s . co m 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:com.openddal.test.BaseTestCase.java
/** * Log an error message./* w ww. j av a 2 s.co m*/ * * @param s the message * @param e the exception */ public static void logError(String s, Throwable e) { if (e == null) { e = new Exception(s); } System.out.flush(); System.err.println("ERROR: " + s + " " + e.toString() + " ------------------------------"); e.printStackTrace(); // synchronize on this class, because file locks are only visible to // other JVMs synchronized (BaseTestCase.class) { try { // lock FileChannel fc = FilePath.get("error.lock").open("rw"); FileLock lock; while (true) { lock = fc.tryLock(); if (lock != null) { break; } Thread.sleep(10); } // append FileWriter fw = new FileWriter("error.txt", true); PrintWriter pw = new PrintWriter(fw); e.printStackTrace(pw); pw.close(); fw.close(); // unlock lock.release(); } catch (Throwable t) { t.printStackTrace(); } } System.err.flush(); }
From source file:cn.codepub.redis.directory.RedisLockFactory.java
@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() + "]!"); }// w ww. j a va2 s.c o m 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); } }
From source file:net.yacy.yacy.java
/** * Starts up the whole application. Sets up all datastructures and starts * the main threads.//from w ww. j av a 2 s. c o m * * @param homePath Root-path where all information is to be found. * @param startupFree free memory at startup time, to be used later for statistics */ private static void startup(final File dataHome, final File appHome, final long startupMemFree, final long startupMemTotal, final boolean gui) { String tmpdir = null; try { // start up System.out.println(copyright); System.out.println(hline); // ensure that there is a DATA directory, if not, create one and if that fails warn and die mkdirsIfNeseccary(dataHome); mkdirsIfNeseccary(appHome); File f = new File(dataHome, "DATA/"); mkdirsIfNeseccary(f); if (!(f.exists())) { System.err.println("Error creating DATA-directory in " + dataHome.toString() + " . Please check your write-permission for this folder. YaCy will now terminate."); System.exit(-1); } // set jvm tmpdir to a subdir for easy cleanup (as extensive use file.deleteonexit waists memory during long runs, as todelete files names are collected and never cleaned up during runtime) // keep this as earlier as possible, as any other class can use the "java.io.tmpdir" property, even the log manager, when the log file pattern uses "%t" as an alias for the tmp directory try { tmpdir = java.nio.file.Files.createTempDirectory("yacy-tmp-").toString(); // creates sub dir in jvm's temp (see System.property "java.io.tempdir") System.setProperty("java.io.tmpdir", tmpdir); } catch (IOException ex) { } // setting up logging f = new File(dataHome, "DATA/LOG/"); mkdirsIfNeseccary(f); f = new File(dataHome, "DATA/LOG/yacy.logging"); final File f0 = new File(appHome, "defaults/yacy.logging"); if (!f.exists() || f0.lastModified() > f.lastModified()) try { Files.copy(f0, f); } catch (final IOException e) { System.out.println("could not copy yacy.logging"); } try { ConcurrentLog.configureLogging(dataHome, new File(dataHome, "DATA/LOG/yacy.logging")); } catch (final IOException e) { System.out.println("could not find logging properties in homePath=" + dataHome); ConcurrentLog.logException(e); } ConcurrentLog.config("STARTUP", "YaCy version: " + yacyBuildProperties.getVersion() + "/" + yacyBuildProperties.getSVNRevision()); ConcurrentLog.config("STARTUP", "Java version: " + System.getProperty("java.version", "no-java-version")); ConcurrentLog.config("STARTUP", "Operation system: " + System.getProperty("os.name", "unknown")); ConcurrentLog.config("STARTUP", "Application root-path: " + appHome); ConcurrentLog.config("STARTUP", "Data root-path: " + dataHome); ConcurrentLog.config("STARTUP", "Time zone: UTC" + GenericFormatter.UTCDiffString() + "; UTC+0000 is " + System.currentTimeMillis()); ConcurrentLog.config("STARTUP", "Maximum file system path length: " + OS.maxPathLength); f = new File(dataHome, "DATA/yacy.running"); final String conf = "DATA/SETTINGS/yacy.conf".replace("/", File.separator); if (!f.createNewFile()) ConcurrentLog.severe("STARTUP", "WARNING: the file " + f + " can not be created!"); try { new FileOutputStream(f).write(Integer.toString(OS.getPID()).getBytes()); } catch (final Exception e) { } // write PID f.deleteOnExit(); FileChannel channel = null; FileLock lock = null; try { channel = new RandomAccessFile(f, "rw").getChannel(); lock = channel.tryLock(); // lock yacy.running } catch (final Exception e) { } try { sb = new Switchboard(dataHome, appHome, "defaults/yacy.init".replace("/", File.separator), conf); } catch (final RuntimeException e) { ConcurrentLog.severe("STARTUP", "YaCy cannot start: " + e.getMessage(), e); System.exit(-1); } //sbSync.V(); // signal that the sb reference was set // switch the memory strategy MemoryControl.setStandardStrategy(sb.getConfigBool("memory.standardStrategy", true)); // save information about available memory at startup time sb.setConfig("memoryFreeAfterStartup", startupMemFree); sb.setConfig("memoryTotalAfterStartup", startupMemTotal); // start gui if wanted if (gui) YaCyApp.start("localhost", sb.getLocalPort()); // hardcoded, forced, temporary value-migration sb.setConfig("htTemplatePath", "htroot/env/templates"); double oldVer; try { String tmpversion = sb.getConfig(Seed.VERSION, ""); if (tmpversion.isEmpty()) { // before 1.83009737 only the svnRevision nr was in config (like 9737) tmpversion = yacyBuildProperties.getVersion(); int oldRev = Integer.parseInt(sb.getConfig("svnRevision", "0")); if (oldRev > 1) { oldVer = Double.parseDouble(tmpversion) + oldRev / 100000000.0; } else { oldVer = Double.parseDouble(yacyBuildProperties.getLongVersion()); // failsafe (assume current version = no migration) } } else { oldVer = Double.parseDouble(tmpversion); } } catch (final NumberFormatException e) { oldVer = 0.0d; } final double newRev = Double.parseDouble(yacyBuildProperties.getLongVersion()); sb.setConfig(Seed.VERSION, yacyBuildProperties.getLongVersion()); sb.setConfig("applicationRoot", appHome.toString()); sb.setConfig("dataRoot", dataHome.toString()); // create some directories final File htRootPath = new File(appHome, sb.getConfig(SwitchboardConstants.HTROOT_PATH, SwitchboardConstants.HTROOT_PATH_DEFAULT)); mkdirIfNeseccary(htRootPath); htDocsPath = sb.getDataPath(SwitchboardConstants.HTDOCS_PATH, SwitchboardConstants.HTDOCS_PATH_DEFAULT); mkdirIfNeseccary(htDocsPath); //final File htTemplatePath = new File(homePath, sb.getConfig("htTemplatePath","htdocs")); // copy the donate iframe (better to copy this once here instead of doing this in an actual iframe in the search result) importDonationIFrame(sb, htDocsPath); // create default notifier picture File notifierFile = new File(htDocsPath, "notifier.gif"); if (!notifierFile.exists()) try { Files.copy(new File(htRootPath, "env/grafics/empty.gif"), notifierFile); } catch (final IOException e) { } final File htdocsReadme = new File(htDocsPath, "readme.txt"); if (!(htdocsReadme.exists())) try { FileUtils.copy(("This is your root directory for individual Web Content\r\n" + "\r\n" + "Please place your html files into the www subdirectory.\r\n" + "The URL of that path is either\r\n" + "http://www.<your-peer-name>.yacy or\r\n" + "http://<your-ip>:<your-port>/www\r\n" + "\r\n" + "Other subdirectories may be created; they map to corresponding sub-domains.\r\n" + "This directory shares it's content with the applications htroot path, so you\r\n" + "may access your yacy search page with\r\n" + "http://<your-peer-name>.yacy/\r\n" + "\r\n").getBytes(), htdocsReadme); } catch (final IOException e) { System.out.println("Error creating htdocs readme: " + e.getMessage()); } shareDefaultPath = new File(htDocsPath, "share"); mkdirIfNeseccary(shareDefaultPath); shareDumpDefaultPath = new File(shareDefaultPath, "dump"); mkdirIfNeseccary(shareDumpDefaultPath); migration.migrate(sb, oldVer, newRev); // delete old release files final int deleteOldDownloadsAfterDays = (int) sb.getConfigLong("update.deleteOld", 30); yacyRelease.deleteOldDownloads(sb.releasePath, deleteOldDownloadsAfterDays); // set user-agent HTTPClient.setDefaultUserAgent(ClientIdentification.yacyInternetCrawlerAgent.userAgent); // start main threads final int port = sb.getLocalPort(); try { // start http server YaCyHttpServer httpServer; httpServer = new Jetty9HttpServerImpl(port); httpServer.startupServer(); sb.setHttpServer(httpServer); // TODO: this has no effect on Jetty (but needed to reflect configured value and limit is still used) ConnectionInfo.setServerMaxcount(sb.getConfigInt("connectionsMax", ConnectionInfo.getMaxcount())); ConcurrentLog.info("STARTUP", httpServer.getVersion()); // open the browser window final boolean browserPopUpTrigger = sb .getConfig(SwitchboardConstants.BROWSER_POP_UP_TRIGGER, "true").equals("true"); if (browserPopUpTrigger) try { final String browserPopUpPage = sb.getConfig(SwitchboardConstants.BROWSER_POP_UP_PAGE, "ConfigBasic.html"); //boolean properPW = (sb.getConfig(SwitchboardConstants.ADMIN_ACCOUNT, "").isEmpty()) && (sb.getConfig(httpd.ADMIN_ACCOUNT_B64MD5, "").length() > 0); //if (!properPW) browserPopUpPage = "ConfigBasic.html"; /* YaCy main startup process must not hang because browser opening is long or fails. * Let's open try opening the browser in a separate thread */ new Thread("Browser opening") { @Override public void run() { Browser.openBrowser(("http://localhost:" + port) + "/" + browserPopUpPage); } }.start(); // Browser.openBrowser((server.withSSL()?"https":"http") + "://localhost:" + serverCore.getPortNr(port) + "/" + browserPopUpPage); } catch (final Throwable e) { // cannot open browser. This may be normal in headless environments //Log.logException(e); } // enable browser popup, http server is ready now sb.tray.setReady(); //regenerate Locales from Translationlist, if needed final File locale_source = sb.getAppPath("locale.source", "locales"); final String lang = sb.getConfig("locale.language", ""); // on lang=browser all active translation should be checked (because any could be requested by client) List<String> langlist; if (lang.endsWith("browser")) langlist = Translator.activeTranslations(); // get all translated languages else { langlist = new ArrayList<String>(); langlist.add(lang); } for (String tmplang : langlist) { if (!tmplang.equals("") && !tmplang.equals("default") && !tmplang.equals("browser")) { //locale is used String currentRev = null; BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(new FileInputStream( new File(sb.getDataPath("locale.translated_html", "DATA/LOCALE/htroot"), tmplang + "/version")))); currentRev = br.readLine(); // may return null } catch (final IOException e) { //Error } finally { try { br.close(); } catch (IOException ioe) { ConcurrentLog.warn("STARTUP", "Could not close " + tmplang + " version file"); } } if (currentRev == null || !currentRev.equals(sb.getConfig(Seed.VERSION, ""))) { try { //is this another version?! final File sourceDir = new File(sb.getConfig(SwitchboardConstants.HTROOT_PATH, SwitchboardConstants.HTROOT_PATH_DEFAULT)); final File destDir = new File( sb.getDataPath("locale.translated_html", "DATA/LOCALE/htroot"), tmplang); if (new TranslatorXliff().translateFilesRecursive(sourceDir, destDir, new File(locale_source, tmplang + ".lng"), "html,template,inc", "locale")) { //translate it //write the new Versionnumber final BufferedWriter bw = new BufferedWriter( new PrintWriter(new FileWriter(new File(destDir, "version")))); bw.write(sb.getConfig(Seed.VERSION, "Error getting Version")); bw.close(); } } catch (final IOException e) { } } } } // initialize number formatter with this locale if (!lang.equals("browser")) // "default" is handled by .setLocale() Formatter.setLocale(lang); // registering shutdown hook ConcurrentLog.config("STARTUP", "Registering Shutdown Hook"); final Runtime run = Runtime.getRuntime(); run.addShutdownHook(new shutdownHookThread(sb, shutdownSemaphore)); // save information about available memory after all initializations //try { sb.setConfig("memoryFreeAfterInitBGC", MemoryControl.free()); sb.setConfig("memoryTotalAfterInitBGC", MemoryControl.total()); System.gc(); sb.setConfig("memoryFreeAfterInitAGC", MemoryControl.free()); sb.setConfig("memoryTotalAfterInitAGC", MemoryControl.total()); //} catch (final ConcurrentModificationException e) {} // wait for server shutdown try { sb.waitForShutdown(); } catch (final Exception e) { ConcurrentLog.severe("MAIN CONTROL LOOP", "PANIC: " + e.getMessage(), e); } // shut down Array.terminate(); ConcurrentLog.config("SHUTDOWN", "caught termination signal"); httpServer.stop(); ConcurrentLog.config("SHUTDOWN", "server has terminated"); sb.close(); } catch (final Exception e) { ConcurrentLog.severe("STARTUP", "Unexpected Error: " + e.getClass().getName(), e); //System.exit(1); } if (lock != null) lock.release(); if (channel != null) channel.close(); } catch (final Exception ee) { ConcurrentLog.severe("STARTUP", "FATAL ERROR: " + ee.getMessage(), ee); } finally { } if (tmpdir != null) FileUtils.deletedelete(new File(tmpdir)); // clean up temp dir (set at startup as subdir of system.propery "java.io.tmpdir") ConcurrentLog.config("SHUTDOWN", "goodbye. (this is the last line)"); ConcurrentLog.shutdown(); shutdownSemaphore.release(1000); try { System.exit(0); } catch (final Exception e) { } // was once stopped by de.anomic.net.ftpc$sm.checkExit(ftpc.java:1790) }
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 v a 2 s .c o m*/ * @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.espirit.moddev.examples.uxbridge.newsdrilldown.jpa.NewsHandler.java
/** * Deletes a newsdrilldown from the db.//from ww w . jav a 2 s . co 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:com.clustercontrol.agent.job.PublicKeyThread.java
/** * ?Authorized_key????<BR>//from w ww. ja v a 2 s .c o m * * @param publicKey * @return */ private synchronized boolean addKey(String publicKey) { m_log.debug("add key start"); if (SKIP_KEYFILE_UPDATE) { m_log.info("skipped appending publicKey"); return true; } //??? String fileName = AgentProperties.getProperty(execUser.toLowerCase() + AUTHORIZED_KEY_PATH); m_log.debug("faileName" + fileName); if (fileName == null || fileName.length() == 0) return false; //File? File fi = new File(fileName); RandomAccessFile randomAccessFile = null; FileChannel channel = null; FileLock lock = null; boolean add = false; try { //RandomAccessFile? randomAccessFile = new RandomAccessFile(fi, "rw"); //FileChannel? channel = randomAccessFile.getChannel(); // for (int i = 0; i < (FILELOCK_TIMEOUT / FILELOCK_WAIT); i++) { if (null != (lock = channel.tryLock())) { break; } m_log.info("waiting for locked file... [" + (i + 1) + "/" + (FILELOCK_TIMEOUT / FILELOCK_WAIT) + " : " + fileName + "]"); Thread.sleep(FILELOCK_WAIT); } if (null == lock) { m_log.warn("file locking timeout."); return false; } // (?) synchronized (authKeyLock) { //?? channel.position(channel.size()); //? String writeData = "\n" + publicKey; // m_log.debug("add key : " + writeData); //????? ByteBuffer buffer = ByteBuffer.allocate(512); //??? buffer.clear(); buffer.put(writeData.getBytes()); buffer.flip(); channel.write(buffer); } add = true; } catch (Exception e) { m_log.error(e); } finally { try { if (channel != null) { channel.close(); } if (randomAccessFile != null) { randomAccessFile.close(); } if (lock != null) { // lock.release(); } } catch (Exception e) { } } return add; }
From source file:com.clustercontrol.agent.job.PublicKeyThread.java
/** * ?Authorized_key????<BR>/*from w w w.ja va 2 s . co m*/ * * @param publicKey * @return true : ?false: */ private synchronized boolean deleteKey(String publicKey) { m_log.debug("delete key start"); if (SKIP_KEYFILE_UPDATE) { m_log.info("skipped deleting publicKey"); return true; } Charset charset = Charset.forName("UTF-8"); CharsetEncoder encoder = charset.newEncoder(); CharsetDecoder decoder = charset.newDecoder(); //??? String fileName = AgentProperties.getProperty(execUser.toLowerCase() + AUTHORIZED_KEY_PATH); if (fileName == null || fileName.length() == 0) return false; //File? File fi = new File(fileName); RandomAccessFile randomAccessFile = null; FileChannel channel = null; FileLock lock = null; boolean delete = false; try { //RandomAccessFile? randomAccessFile = new RandomAccessFile(fi, "rw"); //FileChannel? channel = randomAccessFile.getChannel(); // for (int i = 0; i < (FILELOCK_TIMEOUT / FILELOCK_WAIT); i++) { if (null != (lock = channel.tryLock())) { break; } m_log.info("waiting for locked file... [" + (i + 1) + "/" + (FILELOCK_TIMEOUT / FILELOCK_WAIT) + " : " + fileName + "]"); Thread.sleep(FILELOCK_WAIT); } if (null == lock) { m_log.warn("file locking timeout."); return false; } // (?) synchronized (authKeyLock) { //?? ByteBuffer buffer = ByteBuffer.allocate((int) channel.size()); //?? channel.read(buffer); // ???????????0? buffer.flip(); //?? String contents = decoder.decode(buffer).toString(); // ? m_log.debug("contents " + contents.length() + " : " + contents); //?? List<String> keyCheck = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(contents, "\n"); while (tokenizer.hasMoreTokens()) { keyCheck.add(tokenizer.nextToken()); } //?????? int s = keyCheck.lastIndexOf(publicKey); if (s != -1) { // ? m_log.debug("remobe key : " + keyCheck.get(s)); keyCheck.remove(s); } //????? encoder.reset(); buffer.clear(); int i; if (keyCheck.size() > 0) { for (i = 0; i < keyCheck.size() - 1; i++) { encoder.encode(CharBuffer.wrap(keyCheck.get(i) + "\n"), buffer, false); } encoder.encode(CharBuffer.wrap(keyCheck.get(i)), buffer, true); } //??? buffer.flip(); channel.truncate(0); channel.position(0); channel.write(buffer); } delete = true; } catch (IOException e) { m_log.error(e.getMessage(), e); } catch (RuntimeException e) { m_log.error(e.getMessage(), e); } catch (InterruptedException e) { m_log.error(e.getMessage(), e); } finally { try { if (channel != null) { channel.close(); } if (randomAccessFile != null) { randomAccessFile.close(); } //? if (lock != null) { lock.release(); } } catch (Exception e) { } } return delete; }
From source file:com.mindquarry.desktop.client.MindClient.java
private void createLock() { File f = new File(LOCK_FILE); try {// w w w.j a v a 2 s . co m if (!f.exists()) { f.createNewFile(); } } catch (IOException e) { log.error("Cannot create lock file '" + f.getAbsolutePath() + "'", e); //$NON-NLS-1$ } // this is the recommended way to implement locking, it doesn't leave // a lock file, not even if the app crashes: FileChannel fileChannel; try { fileChannel = (new FileOutputStream(f)).getChannel(); fileLock = fileChannel.tryLock(); if (fileLock == null) { MessageDialog dlg = new MessageDialog(getShell(), I18N.getString("Mindquarry Client already running"), null, I18N.getString("The Mindquarry Desktop Client seems to be running " + "already. Only one instance of the Desktop Client can be " + "running at a time. If you are sure that the Desktop Client " + "isn't running, select 'Start anyway'."), MessageDialog.ERROR, new String[] { I18N.getString("Exit"), I18N.getString("Start anyway") }, 0); int result = dlg.open(); if (result == 0) { System.exit(1); } else { log.warn("Starting despite lock file"); //$NON-NLS-1$ } } else { log.info("Aquired lock: " + fileLock); } } catch (IOException e) { log.error("Cannot create lock on lock file '" + f.getAbsolutePath(), e); } // Note: no need to delete the lock, the JVM will care about that }