コード例 #1
0
  @Test
  public void testLockNegative() throws IOException {
    FileChannel channel = channel(regularFile(0), READ, WRITE);

    try {
      channel.lock(-1, 10, true);
      fail();
    } catch (IllegalArgumentException expected) {
    }

    try {
      channel.lock(0, -1, true);
      fail();
    } catch (IllegalArgumentException expected) {
    }

    try {
      channel.tryLock(-1, 10, true);
      fail();
    } catch (IllegalArgumentException expected) {
    }

    try {
      channel.tryLock(0, -1, true);
      fail();
    } catch (IllegalArgumentException expected) {
    }
  }
コード例 #2
0
  /** @tests java.nio.channels.FileLock#release() */
  public void test_release() throws Exception {
    File file = File.createTempFile("test", "tmp");
    file.deleteOnExit();
    FileOutputStream fout = new FileOutputStream(file);
    FileChannel fileChannel = fout.getChannel();
    FileLock fileLock = fileChannel.lock();
    fileChannel.close();
    try {
      fileLock.release();
      fail("should throw ClosedChannelException");
    } catch (ClosedChannelException e) {
      // expected
    }

    // release after release
    fout = new FileOutputStream(file);
    fileChannel = fout.getChannel();
    fileLock = fileChannel.lock();
    fileLock.release();
    fileChannel.close();
    try {
      fileLock.release();
      fail("should throw ClosedChannelException");
    } catch (ClosedChannelException e) {
      // expected
    }
  }
コード例 #3
0
  /**
   * Copy the content of the source file to the destination file
   *
   * @param aSrcFile Source file. May not be <code>null</code>.
   * @param aDestFile Destination file. May not be <code>null</code>.
   * @return {@link ESuccess}
   */
  @Nonnull
  private static ESuccess _copyFile(@Nonnull final File aSrcFile, @Nonnull final File aDestFile) {
    final FileChannel aSrcChannel = FileUtils.getFileReadChannel(aSrcFile);
    if (aSrcChannel == null) return ESuccess.FAILURE;

    try {
      final FileChannel aDstChannel = FileUtils.getFileWriteChannel(aDestFile, EAppend.TRUNCATE);
      if (aDstChannel == null) return ESuccess.FAILURE;

      try {
        FileLock aSrcLock = null;
        FileLock aDestLock = null;
        try {
          final long nBytesToRead = aSrcChannel.size();

          // Shared read lock and exclusive write lock
          aSrcLock = aSrcChannel.lock(0, nBytesToRead, true);
          aDestLock = aDstChannel.lock();

          // Main copying - the loop version is much quicker than then
          // transferTo with full size!
          long nBytesWritten = 0;
          final long nChunkSize = 1 * CGlobal.BYTES_PER_MEGABYTE;
          while (nBytesWritten < nBytesToRead)
            nBytesWritten += aSrcChannel.transferTo(nBytesWritten, nChunkSize, aDstChannel);

          if (nBytesToRead != nBytesWritten) {
            s_aLogger.error(
                "Failed to copy file. Meant to read "
                    + nBytesToRead
                    + " bytes but wrote "
                    + nBytesWritten);
            return ESuccess.FAILURE;
          }
          return ESuccess.SUCCESS;
        } catch (final IOException ex) {
          throw new IllegalStateException(
              "Failed to copy from " + aSrcFile + " to " + aDestFile, ex);
        } finally {
          // Unlock
          ChannelUtils.release(aDestLock);
          ChannelUtils.release(aSrcLock);
        }
      } finally {
        ChannelUtils.close(aDstChannel);
      }
    } finally {
      ChannelUtils.close(aSrcChannel);
    }
  }
コード例 #4
0
  /* (non-Javadoc)
   * @see com.ongraphdb.store.DiskSore1#start()
   */
  public void start() throws IOException {
    File file = new File(dataFileName);
    boolean newStore = file.exists() ? false : true;

    RandomAccessFile dataFile = new RandomAccessFile(dataFileName, "rw");
    dataFile.setLength(initialFileSize);
    dataChannel = dataFile.getChannel();
    dataLock = dataChannel.lock();
    mappedDataBuffer = dataChannel.map(MapMode.READ_WRITE, 0, dataMappedMemorySize);

    if (newStore) {
      nextPosition = NEXT_BYTES;
      mappedDataBuffer.putInt(nextPosition);
    } else {
      nextPosition = mappedDataBuffer.getInt();
    }
    shutdownHookThread =
        new Thread() {
          public void run() {
            try {
              mappedDataBuffer.force();
              dataLock.release();
              dataChannel.close();
              unmap(mappedDataBuffer);
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    Runtime.getRuntime().addShutdownHook(shutdownHookThread);
  }
コード例 #5
0
  private boolean lock(int flg) {

    try {
      if (fc != null) {
        if (flg == TRY_LOCK_FLG) {
          fl = fc.tryLock();
        } else if (flg == LOCK_FLG) {
          fl = fc.lock();
        }
        if (fl == null) {
          return false;
        }
        return true;
      } else {
        return false;
      }
    } catch (IOException e) {
      e.printStackTrace();
      try {
        fl.release();
      } catch (IOException ex) {
        ex.printStackTrace();
      }
      return false;
    }
  }
コード例 #6
0
  /** @param args */
  public static void main(String[] args) throws Exception {

    // 读取的 地址
    File fInput = new File(Config.inputAdd);

    // 读取流
    FileInputStream fis = new FileInputStream(fInput);

    // 读取 管道
    FileChannel inputChannel = fis.getChannel();
    // lock方式 加 共享锁

    System.out.println("主线程 在 控制文件fInput - 30秒 , 当前时间子线程 - >" + new Date());
    FileLock lock = inputChannel.lock(0, fInput.length(), true);
    System.out.println("子线程 对 fInput 加上锁了。加上的时间为: " + new Date());

    if (null != lock) {
      System.out.println("子线程开始执行 锁里面的操作了");
    } else {
      System.out.println("按道理说 这句话 永远 不应该被打印 的.....");
    }

    lock.release();

    // 释放资源
    fis.close();
    inputChannel.close();
  }
    public void run() {
      try {
        /* Get FileLocks. */
        FileChannel channel = lockFile.getChannel();
        FileLock lockA = channel.lock(1, 1, false);
        FileLock lockC = channel.lock(3, 1, false);

        ReplicatedEnvironment master = getMaster();
        doWork(master, dbName, 1);
        /* Release lock A so that read process can do reads. */
        lockA.release();

        /* Make sure read process get lock B before this process. */
        Thread.sleep(sleepTime);

        /* Get lock B means read process finish reading, do updates. */
        FileLock lockB = getLockWithReTry(channel, 2, 1);
        doWork(master, dbName, 101);

        /* Release lock B and lock C. */
        lockB.release();
        lockC.release();
      } catch (Exception e) {
        /* Dump exceptions and exit with value 6. */
        e.printStackTrace();
        System.exit(7);
      } finally {
        RepTestUtils.shutdownRepEnvs(repEnvInfo);
        closeLockFile(lockFile);
      }
    }
コード例 #8
0
  /**
   * @param directory
   * @return
   * @throws IOException
   */
  FileLock acquireLock(File directory) throws IOException {
    // Get a file channel for the file
    File file = new File(directory, LOCK_FILE);
    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.
    while (!lock.isValid()) {
      try {
        lock = channel.tryLock();
      } catch (OverlappingFileLockException e) {
        // File is already locked in this thread or virtual machine
      }
      // wait for the other process to unlock it, should take a couple of seconds
      try {
        Thread.sleep(500);
      } catch (InterruptedException e) {
        // someone waked us earlier, no problem
      }
    }

    return lock;
  }
コード例 #9
0
ファイル: ReadLock.java プロジェクト: erinkhoo/imhotep
  private static void acquireReadLock(Map<File, RandomAccessFile> lockFileMap, File indexDir)
      throws IOException, LockAquisitionException {
    final File writeLock = new File(indexDir, "delete.lock");
    writeLock.createNewFile();
    while (true) {
      synchronized (lockFileMap) {
        RandomAccessFile raf = lockFileMap.get(indexDir);
        if (raf == null) {
          raf = new RandomAccessFile(writeLock, "r");
          lockFileMap.put(indexDir, raf);
        } else {
          throw new AlreadyOpenException();
        }

        final FileChannel channel = raf.getChannel();
        try {
          channel.lock(0, Long.MAX_VALUE, true);
          if (indexDir.exists()) {
            return;
          }
          lockFileMap.remove(indexDir);
          Closeables2.closeQuietly(raf, log);
          throw new ShardDeletedException();
        } catch (OverlappingFileLockException e) {
          lockFileMap.remove(indexDir);
          Closeables2.closeQuietly(raf, log);
          throw Throwables.propagate(e);
        } catch (FileLockInterruptionException e) {
          lockFileMap.remove(indexDir);
          Closeables2.closeQuietly(raf, log);
        }
      }
    }
  }
コード例 #10
0
  @Test
  public void testLock() throws IOException {
    FileChannel channel = channel(regularFile(10), READ, WRITE);

    assertNotNull(channel.lock());
    assertNotNull(channel.lock(0, 10, false));
    assertNotNull(channel.lock(0, 10, true));

    assertNotNull(channel.tryLock());
    assertNotNull(channel.tryLock(0, 10, false));
    assertNotNull(channel.tryLock(0, 10, true));

    FileLock lock = channel.lock();
    assertTrue(lock.isValid());
    lock.release();
    assertFalse(lock.isValid());
  }
コード例 #11
0
  public static void main(String args[]) throws IOException {
    if (args.length != 1) {
      System.err.println("Usage: java LockingExample <input file>");
      System.exit(0);
    }

    FileLock sharedLock = null;
    FileLock exclusiveLock = null;

    try {
      RandomAccessFile raf = new RandomAccessFile(args[0], "rw");

      // get the channel for the file
      FileChannel channel = raf.getChannel();

      System.out.println("trying to acquire lock ...");
      // this locks the first half of the file - exclusive
      exclusiveLock = channel.lock(0, raf.length() / 2, SHARED);
      System.out.println("lock acquired ...");

      /** Now modify the data . . . */
      try {
        // sleep for 10 seconds
        Thread.sleep(10000);
      } catch (InterruptedException ie) {
      }

      // release the lock
      exclusiveLock.release();
      System.out.println("lock released ...");

      // this locks the second half of the file - shared
      sharedLock = channel.lock(raf.length() / 2 + 1, raf.length(), SHARED);

      /** Now read the data . . . */

      // release the lock
      sharedLock.release();
    } catch (java.io.IOException ioe) {
      System.err.println(ioe);
    } finally {
      if (exclusiveLock != null) exclusiveLock.release();
      if (sharedLock != null) sharedLock.release();
    }
  }
コード例 #12
0
ファイル: DirectoryLock.java プロジェクト: ihr/sonarqube
 public void lock() {
   try {
     lockRandomAccessFile = new RandomAccessFile(lockFilePath.toFile(), "rw");
     lockChannel = lockRandomAccessFile.getChannel();
     lockFile = lockChannel.lock(0, 1024, false);
   } catch (IOException e) {
     throw new IllegalStateException("Failed to create lock in " + lockFilePath.toString(), e);
   }
 }
コード例 #13
0
  public static void main(String[] args) {

    try {
      String filename = "fileToLock.dat";
      File file = new File(filename);
      file.createNewFile();

      // Creates a random access file stream to read from, and optionally
      // to write to
      FileChannel channel = new RandomAccessFile(file, "rw").getChannel();

      DataOutputStream out2 =
          new DataOutputStream(new BufferedOutputStream(new FileOutputStream(filename)));
      out2.writeDouble(3.14159);
      out2.writeChars("That was pi\n");
      out2.writeBytes("That was pi\n");
      out2.close();

      // Acquire an exclusive lock on this channel's file ( block until
      // the region can be
      // locked, this channel is closed, or the invoking thread is
      // interrupted)
      FileLock lock = channel.lock(0, Long.MAX_VALUE, false);

      System.out.print("Press any key...");
      System.in.read();
      // Attempts to acquire an exclusive lock on this channel's file
      // (does not block, an
      // invocation always returns immediately, either having acquired a
      // lock on the requested
      // region or having failed to do so.
      try {

        lock = channel.tryLock(0, Long.MAX_VALUE, true);
      } catch (OverlappingFileLockException e) {
        // thrown when an attempt is made to acquire a lock on a a file
        // that overlaps
        // a region already locked by the same JVM or when another
        // thread is already
        // waiting to lock an overlapping region of the same file
        System.out.println("Overlapping File Lock Error: " + e.getMessage());
      }

      // tells whether this lock is shared
      boolean isShared = lock.isShared();

      // release the lock
      lock.release();

      // close the channel
      channel.close();

    } catch (IOException e) {
      System.out.println("I/O Error: " + e.getMessage());
    }
  }
コード例 #14
0
  @Override
  public void run() {
    Database database = input.getDatabase();
    Relation<O> relation = database.getRelation(distance.getInputTypeRestriction());
    DistanceQuery<O> distanceQuery = database.getDistanceQuery(relation, distance);
    KNNQuery<O> knnQ = database.getKNNQuery(distanceQuery, DatabaseQuery.HINT_HEAVY_USE);

    // open file.
    try (RandomAccessFile file = new RandomAccessFile(out, "rw");
        FileChannel channel = file.getChannel();
        // and acquire a file write lock
        FileLock lock = channel.lock()) {
      // write magic header
      file.writeInt(KNN_CACHE_MAGIC);

      int bufsize = k * 12 * 2 + 10; // Initial size, enough for 2 kNN.
      ByteBuffer buffer = ByteBuffer.allocateDirect(bufsize);

      FiniteProgress prog =
          LOG.isVerbose() ? new FiniteProgress("Computing kNN", relation.size(), LOG) : null;

      for (DBIDIter it = relation.iterDBIDs(); it.valid(); it.advance()) {
        final KNNList nn = knnQ.getKNNForDBID(it, k);
        final int nnsize = nn.size();

        // Grow the buffer when needed:
        if (nnsize * 12 + 10 > bufsize) {
          while (nnsize * 12 + 10 > bufsize) {
            bufsize <<= 1;
          }
          buffer = ByteBuffer.allocateDirect(bufsize);
        }

        buffer.clear();
        ByteArrayUtil.writeUnsignedVarint(buffer, it.internalGetIndex());
        ByteArrayUtil.writeUnsignedVarint(buffer, nnsize);
        int c = 0;
        for (DoubleDBIDListIter ni = nn.iter(); ni.valid(); ni.advance(), c++) {
          ByteArrayUtil.writeUnsignedVarint(buffer, ni.internalGetIndex());
          buffer.putDouble(ni.doubleValue());
        }
        if (c != nn.size()) {
          throw new AbortException("Sizes did not agree. Cache is invalid.");
        }

        buffer.flip();
        channel.write(buffer);
        LOG.incrementProcessed(prog);
      }
      LOG.ensureCompleted(prog);
      lock.release();
    } catch (IOException e) {
      LOG.exception(e);
    }
    // FIXME: close!
  }
コード例 #15
0
ファイル: FileShareLock01.java プロジェクト: qubo188/EffJava
  /** 演示 用 Channel锁 主文件。 但是 用传统的 io 写入文件 时。是可以写入的。 */
  public static void demo1() throws Exception {

    // 读取的 地址
    File fInput = new File(Config.inputAdd);

    // 创建 一个 读写 操作
    RandomAccessFile raf = new RandomAccessFile(fInput, "rw");
    // 跳至 文件默认 准备 追加
    raf.seek(fInput.length());

    FileChannel channel = raf.getChannel();

    // true 创建 一个 共享锁
    // 如果说 当前 没有其它线程占用。那么这个地方就会返回一个新的 FileLock对象。代表我将文件Config.inputAdd锁定。
    // 如果 被其它人 占用 那么就会成 阻塞 模式。不往下继续执行
    FileLock fileLock = channel.lock(0, fInput.length(), true);
    // 重点------>不要忘记lock 是阻塞方式。也就是说。假如现在有另一个线程在使用着这个文件的资源。
    // 那么执行到这里。就不会 往下 执行的。
    // 直到 另一个线程 释放了 资源。我这个地方 才能返回一个新的 FileLock对象

    if (null != fileLock) {
      System.out.println("已经 获取 到 文件锁");
      // 没有 被其他人 占用。或者说已经释放了。
      // 目前已经被我自己占用

      // 那么第一步 我先读取
      // 已经 数据 一次性 的 读取到 内存映射 mbb当中
      MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_WRITE, 0, fInput.length());

      byte[] temp = new byte[(int) fInput.length()];
      int foot = 0;

      while (mbb.hasRemaining()) {
        temp[foot++] = mbb.get();
      }
      System.out.println(new String(temp));
      System.out.println("数据  读取 完毕");
      // 在上面 锁没有 释放的情况下,我又往这个文件 写入数据了。
      raf.write(temp);
      System.out.println("数据  写入 完毕");

    } else {
      System.out.println("当前 文件 已经 被其它线程锁定 ---这句话 应该是永远也不会被执行的。 ");
    }

    // 释放锁
    fileLock.release();
    System.out.println("文件锁 已经  释放");

    raf.close();
    channel.close();
  }
コード例 #16
0
 public void run() {
   try {
     // Exclusive lock with no overlap:
     FileLock fl = fc.lock(start, end, false);
     System.out.println("Locked: " + start + " to " + end);
     // Perform modification:
     while (buff.position() < buff.limit() - 1) buff.put((byte) (buff.get() + 1));
     fl.release();
     System.out.println("Released: " + start + " to " + end);
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
コード例 #17
0
ファイル: FileAdapter.java プロジェクト: Cherryllu/fourinone
 boolean setLock(String rw, long beginIndex, long bytesNum, boolean s) {
   if (!this.exists()) return false;
   try {
     raf = new RandomAccessFile(this, rw);
     fc = raf.getChannel();
     flk = fc.lock(beginIndex, bytesNum, s);
   } catch (OverlappingFileLockException oe) {
     LogUtil.warn("[SetLock]", "[No effect]", "the region has already been locked");
     return false;
   } catch (Exception e) {
     LogUtil.info("[SetLock]", "[No effect]", e);
     return false;
   }
   return true;
 }
コード例 #18
0
ファイル: FileUtils.java プロジェクト: jancajthaml/rabbit
  /**
   * Unlockes file
   *
   * @param file target File
   */
  @SuppressWarnings("resource")
  public static void unlock(File file) {
    try {
      FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
      FileLock lock = channel.lock();
      try {
        lock = channel.tryLock();
        file.setWritable(true);
      } catch (OverlappingFileLockException e) {
      }

      lock.release();
      channel.close();
    } catch (Exception e) {
    }
  }
コード例 #19
0
ファイル: FileShareLock01.java プロジェクト: qubo188/EffJava
  public static void demo2() throws Exception {

    // 读取的 地址
    File fInput = new File(Config.inputAdd);

    // 读
    FileInputStream fis = new FileInputStream(fInput);

    // 写  true-->以追加的方式
    FileOutputStream fos = new FileOutputStream(fInput, true);

    // 读 管道
    FileChannel inputChannel = fis.getChannel();

    // 写管道
    FileChannel outputChannel = fos.getChannel();

    // 对文件fInput  加  《阻塞》 ->  “共享锁”

    FileLock lock = inputChannel.lock(0, fInput.length(), true);

    // 重点 提示。如果 有其它线程 在对 fInput文件 上锁。那么这个地方是阻塞的。不会往下执行代码

    if (null != lock) {
      // 说明 当前 fInput文件 没有被 上锁。或者说 已经被释放
      System.out.println("文件 没有被上锁 或者 已经被释放锁");

      MappedByteBuffer mbb = inputChannel.map(FileChannel.MapMode.READ_ONLY, 0, fInput.length());
      System.out.println("数据 已经  被 读取 完毕 ");

      outputChannel.write(mbb);
      System.out.println("数据 已经  被 写入 完毕 ");

    } else {
      System.out.println("按道理说 这句话 永远 不应该被打印 的.....");
    }

    // 释放锁
    lock.release();

    fis.close();
    fos.close();
    inputChannel.close();
    outputChannel.close();
  }
コード例 #20
0
  @Test
  public void testWritesInReadOnlyMode() throws IOException {
    FileChannel channel = channel(regularFile(0), READ);

    try {
      channel.write(buffer("111"));
      fail();
    } catch (NonWritableChannelException expected) {
    }

    try {
      channel.write(buffer("111"), 10);
      fail();
    } catch (NonWritableChannelException expected) {
    }

    try {
      channel.write(new ByteBuffer[] {buffer("111"), buffer("111")});
      fail();
    } catch (NonWritableChannelException expected) {
    }

    try {
      channel.write(new ByteBuffer[] {buffer("111"), buffer("111")}, 0, 2);
      fail();
    } catch (NonWritableChannelException expected) {
    }

    try {
      channel.transferFrom(new ByteBufferChannel(bytes("1111")), 0, 4);
      fail();
    } catch (NonWritableChannelException expected) {
    }

    try {
      channel.truncate(0);
      fail();
    } catch (NonWritableChannelException expected) {
    }

    try {
      channel.lock(0, 10, false);
    } catch (NonWritableChannelException expected) {
    }
  }
  static Properties loadFilePrefsImpl(final File file) {
    Properties result = new Properties();
    if (!file.exists()) {
      file.getParentFile().mkdirs();
    } else if (file.canRead()) {
      InputStream in = null;
      FileLock lock = null;
      try {

        FileInputStream istream = new FileInputStream(file);
        // BEGIN android-modified
        in = new BufferedInputStream(istream, 8192);
        // END android-modified
        FileChannel channel = istream.getChannel();
        lock = channel.lock(0L, Long.MAX_VALUE, true);
        Document doc = builder.parse(in);
        // BEGIN android-modified
        NodeList entries = selectNodeList(doc.getDocumentElement(), "entry"); // $NON-NLS-1$
        // END android-modified
        int length = entries.getLength();
        for (int i = 0; i < length; i++) {
          Element node = (Element) entries.item(i);
          String key = node.getAttribute("key"); // $NON-NLS-1$
          String value = node.getAttribute("value"); // $NON-NLS-1$
          result.setProperty(key, value);
        }
        return result;
      } catch (Exception e) {
        e.printStackTrace();
      } finally {
        try {
          lock.release();
        } catch (Exception e) { // ignore
        }
        try {
          in.close();
        } catch (Exception e) { // ignore
        }
      }
    } else {
      file.delete();
    }
    return result;
  }
コード例 #22
0
  /**
   * Opens the given file as a data points file for this RawDataFileImpl instance. If the file is
   * not empty, the TreeMaps supplied as parameters have to describe the mapping of storage IDs to
   * data points in the file.
   */
  public synchronized void openDataPointsFile(File dataPointsFileName) throws IOException {
    if (this.dataPointsFile != null) {
      throw new IOException("Cannot open another data points file, because one is already open");
    }

    this.dataPointsFileName = dataPointsFileName;
    this.dataPointsFile = new RandomAccessFile(dataPointsFileName, "rw");

    // Locks the temporary file so it is not removed when another instance
    // of MZmine is starting. Lock will be automatically released when this
    // instance of MZmine exits.
    FileChannel fileChannel = dataPointsFile.getChannel();
    fileChannel.lock();

    // Unfortunately, deleteOnExit() doesn't work on Windows, see JDK
    // bug #4171239. We will try to remove the temporary files in a
    // shutdown hook registered in the main.ShutDownHook class
    dataPointsFileName.deleteOnExit();
  }
コード例 #23
0
ファイル: LockTest.java プロジェクト: barrysun/java_base
 /**
  * Simulate a series of read-only queries while holding a shared lock on the index area
  *
  * @param fc
  * @throws Exception
  */
 void doQueries(FileChannel fc) throws Exception {
   while (true) {
     System.out.println("trying for shared lock...");
     FileLock lock = fc.lock(INDEX_START, INDEX_SIZE, true);
     int reps = rand.nextInt(60) + 20;
     for (int i = 0; i < reps; i++) {
       int n = rand.nextInt(INDEX_COUNT);
       int position = INDEX_START + (n * SIZEOF_INT);
       buffer.clear();
       fc.read(buffer, position);
       int value = indexBuffer.get(n);
       System.out.println("Index entry " + n + "=" + value);
       Thread.sleep(100);
     }
     lock.release();
     System.out.print("<sleeping>");
     Thread.sleep(rand.nextInt(3000) + 500);
   }
 }
コード例 #24
0
ファイル: FileUtil.java プロジェクト: gitrah/quotation
  public static synchronized void truncateFromBeginning(File f, double pct, File remnant)
      throws IOException {

    RandomAccessFile raf = null;
    RandomAccessFile rafTemp = null;
    File fTemp = null;
    try {
      raf = new RandomAccessFile(f, "rw");
      fTemp = remnant == null ? new File(f.getAbsolutePath() + ".tmp") : remnant;
      rafTemp = fTemp == null ? null : new RandomAccessFile(fTemp, "rw");
      FileChannel fc = raf.getChannel();
      FileChannel fcTemp = rafTemp == null ? fc : rafTemp.getChannel();
      fc.lock();
      long oldSize = f.length();
      long newSize = (long) (oldSize * (1. - pct));
      log.debug("oldSize " + oldSize + ", newSize " + newSize);
      fc.transferTo(oldSize - newSize, newSize, fcTemp); // transfer
      // surviving
      // chunk to temp
      // file
      fcTemp.transferTo(0, newSize, fc); // overwrite beginning of log
      // with surviving chunk
      fc.truncate(newSize); // trim remaining excess from log
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (raf != null) {
          raf.close();
        }
      } finally {
        try {
          if (rafTemp != raf && rafTemp != null) {
            rafTemp.close();
          }
        } finally {
          if (remnant == null && fTemp != null && fTemp.exists()) {
            fTemp.delete();
          }
        }
      }
    }
  }
    public void run() {
      try {
        FileChannel channel = lockFile.getChannel();
        /* Get lock B so that write process waits. */
        FileLock lockB = channel.lock(2, 1, false);

        /* Get lock A means write process finish the first phase. */
        FileLock lockA = getLockWithReTry(channel, 1, 1);
        openEnvironments();

        /* Release lock A and B so that write process can continue. */
        lockB.release();
        lockA.release();

        /* Read records and check the node equality. */
        readRecords(master, prevMasterRecords, replica, prevReplicaRecords);
        doEqualityCompare(prevMasterRecords, prevReplicaRecords, 100);
        closeEnvironments();

        /* Get lock C means second phase of write process finishes. */
        FileLock lockC = getLockWithReTry(channel, 3, 1);
        /* Reopen and read records, then do the compare. */
        openEnvironments();
        readRecords(master, newMasterRecords, replica, newReplicaRecords);
        doEqualityCompare(newMasterRecords, newReplicaRecords, 200);

        /* Do compare between two snapshots. */
        doDiffCompare(prevMasterRecords, newMasterRecords);
        doDiffCompare(prevReplicaRecords, newReplicaRecords);
        lockC.release();
      } catch (Exception e) {
        /* Dump exceptions and exit process with value 7.*/
        e.printStackTrace();
        System.exit(9);
      } finally {
        closeEnvironments();
        closeLockFile(lockFile);
      }
    }
 static void flushFilePrefsImpl(File file, Properties prefs) throws IOException {
   BufferedWriter out = null;
   FileLock lock = null;
   try {
     FileOutputStream ostream = new FileOutputStream(file);
     // BEGIN android-modified
     out = new BufferedWriter(new OutputStreamWriter(ostream, "UTF-8"), 8192); // $NON-NLS-1$
     // END android-modified
     FileChannel channel = ostream.getChannel();
     lock = channel.lock();
     out.write(HEADER);
     out.newLine();
     out.write(FILE_PREFS);
     out.newLine();
     if (prefs.size() == 0) {
       exportEntries(EMPTY_SARRAY, EMPTY_SARRAY, out);
     } else {
       String[] keys = prefs.keySet().toArray(new String[prefs.size()]);
       int length = keys.length;
       String[] values = new String[length];
       for (int i = 0; i < length; i++) {
         values[i] = prefs.getProperty(keys[i]);
       }
       exportEntries(keys, values, out);
     }
     out.flush();
   } finally {
     try {
       lock.release();
     } catch (Exception e) { // ignore
     }
     try {
       if (null != out) {
         out.close();
       }
     } catch (Exception e) { // ignore
     }
   }
 }
コード例 #27
0
  @Test
  public void testReadsInWriteOnlyMode() throws IOException {
    FileChannel channel = channel(regularFile(0), WRITE);

    try {
      channel.read(buffer("111"));
      fail();
    } catch (NonReadableChannelException expected) {
    }

    try {
      channel.read(buffer("111"), 10);
      fail();
    } catch (NonReadableChannelException expected) {
    }

    try {
      channel.read(new ByteBuffer[] {buffer("111"), buffer("111")});
      fail();
    } catch (NonReadableChannelException expected) {
    }

    try {
      channel.read(new ByteBuffer[] {buffer("111"), buffer("111")}, 0, 2);
      fail();
    } catch (NonReadableChannelException expected) {
    }

    try {
      channel.transferTo(0, 10, new ByteBufferChannel(buffer("111")));
      fail();
    } catch (NonReadableChannelException expected) {
    }

    try {
      channel.lock(0, 10, true);
    } catch (NonReadableChannelException expected) {
    }
  }
コード例 #28
0
  @SuppressWarnings("resource")
  protected void openFile() throws IOException {
    synchronized (locked) {
      while (locked.containsKey(filename) && locked.get(filename)) {
        try {
          locked.wait();
        } catch (InterruptedException e) {
        }
      }
      locked.put(filename, true);

      File file = new File(this.filename);
      if (!file.exists()) {
        locked.put(filename, false);
        locked.notifyAll();
        throw new IllegalStateException(
            "Warning: File doesn't exist (anymore):'" + this.filename + "'");
      }

      channel = new RandomAccessFile(file, "rw").getChannel();
      try {
        // TODO: add support for shared locks, allowing parallel reading
        // operations.
        lock = channel.lock();

      } catch (Exception e) {
        channel.close();
        channel = null;
        lock = null;
        locked.put(filename, false);
        locked.notifyAll();
        throw new IllegalStateException("error, couldn't obtain file lock on:" + filename, e);
      }
      fis = new BufferedInputStream(Channels.newInputStream(channel));
      fos = new BufferedOutputStream(Channels.newOutputStream(channel));
    }
  }
コード例 #29
0
  public static void main(String args[]) throws Exception {
    // Get file channel
    RandomAccessFile raf = new RandomAccessFile("usefilelocks.txt", "rw");
    FileChannel fc = raf.getChannel();

    // Get lock
    System.out.println("trying to get lock");
    FileLock lock = fc.lock(start, end, false);
    System.out.println("got lock!");

    // Pause
    System.out.println("pausing");
    try {
      Thread.sleep(3000);
    } catch (InterruptedException ie) {
    }

    // Release lock
    System.out.println("going to release lock");
    lock.release();
    System.out.println("released lock");

    raf.close();
  }
コード例 #30
0
 /** @tests java.nio.channels.FileLock#isValid() */
 public void test_isValid() throws IOException {
   FileLock fileLock = readWriteChannel.lock();
   assertTrue(fileLock.isValid());
   fileLock.release();
   assertFalse(fileLock.isValid());
 }