Package java.util.concurrent.locks

Examples of java.util.concurrent.locks.ReentrantLock


      // I'm recreating the lock object when we return to the pool
      // because it looks too nasty to expect the connection handle
      // to unlock properly in certain race conditions
      // where the dissociation of the managed connection is "random".
      lock = new ReentrantLock(true);
   }
View Full Code Here


      }
      // I'm recreating the lock object when we return to the pool
      // because it looks too nasty to expect the connection handle
      // to unlock properly in certain race conditions
      // where the dissociation of the managed connection is "random".
      lock = new ReentrantLock(true);
   }
View Full Code Here

   */
  public void waitFor(long t)
  {
    if (_state == STATE_IDLE)
      return;
    final Lock lock = new ReentrantLock();
    final java.util.concurrent.locks.Condition isIdle = lock.newCondition();
    StateChangeListener listener = new StateChangeListener()
    {

      public void stateChange(int newState, int oldState)
      {
        lock.lock();
        isIdle.signal();
        lock.unlock();
      }

    };
    this.addStateChangeListener(STATE_IDLE, listener);
    if (_state != STATE_IDLE)
      try
      {
        lock.lock();
        isIdle.await(t, TimeUnit.MILLISECONDS);
      }
      catch (InterruptedException e)
      {
        e.printStackTrace();
        Thread.currentThread().interrupt();
      }
    lock.unlock();
    this.removeStateChangeListener(listener);
  }
View Full Code Here

    return new InputStream()
    {

      boolean        closed  = false;
      boolean        opened  = false;
      Lock        lock  = new ReentrantLock();
      RandomAccessFile  raf;
      ByteBuffer      buf;
      ByteBuffer      posBuf;
      ByteBuffer      lockBuf;

      synchronized void open()
      {
        if (opened)
          return;
        while (!opened && !closed)
        {
          lock.lock();
          if (file.exists())
            try
            {
              // System.out.println("open "+file);
              if (raf == null)
                raf = new RandomAccessFile(file, "r");
              buf = raf.getChannel().map(FileChannel.MapMode.READ_ONLY, 5, CyclicBufferFilePrintStream.length - 5);
              posBuf = raf.getChannel().map(FileChannel.MapMode.READ_ONLY, 1, 4);
              lockBuf = raf.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, 1);
              opened = true;
            }
            catch (Exception ex)
            {
              System.out.println(ex.getMessage());
            }
          lock.unlock();
          if (!opened)
            try
            {
              Thread.sleep(200);
            }
            catch (InterruptedException e)
            {
              e.printStackTrace();
              Thread.currentThread().interrupt();
            }
        }

      }

      @Override
      public void close()
      {
        // lock.lock();
        closed = true;
        try
        {
          if (raf != null)
            raf.close();
          buf = null;
          System.gc();
          Thread.yield();
        }
        catch (IOException e)
        {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        // lock.unlock();
      }

      @Override
      public int read() throws IOException
      {
        if (!buf.hasRemaining())
        {
          buf.position(0);
        }
        while (getPosition() == buf.position() && !closed)
        {
          try
          {
            Thread.sleep(100);
          }
          catch (InterruptedException e)
          {
            e.printStackTrace();
            return -1;
          }
        }
        if (closed)
        {
          return -1;
        }
        return buf.get();
      }

      private int getPosition()
      {
        posBuf.position(0);
        waitUnlocked();
        return posBuf.getInt();
      }

      private void waitUnlocked()
      {
        return;
        /*
         * lockBuf.position(0); boolean free = lockBuf.get() == 0; while
         * (!free) { try { Thread.sleep(50); } catch
         * (InterruptedException e) { // TODO Auto-generated catch block
         * e.printStackTrace(); return; } lockBuf.position(0); free =
         * lockBuf.get() == 0; }
         */
      }

      @Override
      public int read(byte[] bytes, int off, int len) throws IOException
      {
        // System.out.println("read "+buf.position());
        open();
        lock.lock();
        if (!buf.hasRemaining())
        {
          buf.position(0);
        }
        while (!closed && getPosition() == buf.position())
        {
          try
          {
            lock.unlock();
            Thread.sleep(100);
            lock.lock();
          }
          catch (InterruptedException e)
          {
            e.printStackTrace();
            lock.unlock();
            return -1;
          }
        }
        if (closed)
        {
          lock.unlock();
          return -1;
        }
        int toRead = getPosition() - buf.position();
        if (toRead < 0)
          toRead = buf.remaining();
        if (toRead > len)
          toRead = len;
        buf.get(bytes, off, toRead);
        lock.unlock();
        return toRead;
      }
    };
  }
View Full Code Here

    System.setOut(aPrintStream); // catches System.out messages
    System.setErr(aPrintStream); // catches error messages

    // signal condition if continue button hit
    final Lock lock = new ReentrantLock();
    final Condition cont = lock.newCondition();

    wsform._GO_BUTTON.addActionListener(new ActionListener()
    {

      public void actionPerformed(ActionEvent e)
      {
        lock.lock();
        cont.signal();
        lock.unlock();
      }

    });

    wsform._SHOW_CONF_BUTTON.addActionListener(new ActionListener()
    {

      public void actionPerformed(ActionEvent e)
      {
        showFile(configuration);
      }

    });

    wsform._SELECT_FOLDER_BUTTON.addActionListener(new ActionListener()
    {

      public void actionPerformed(ActionEvent e)
      {
        JFileChooser fc = new JFileChooser();
        fc.setCurrentDirectory(new File("."));
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.setAcceptAllFileFilterUsed(false);
        int retval = fc.showOpenDialog(wsform);

        if (retval == JFileChooser.APPROVE_OPTION)
        {
          // ... The user selected a file, get it, use it.
          File file = fc.getSelectedFile();

          // ... Update user interface.
          try
          {
            wsform._INSTALL_FOLDER.setText(file.getCanonicalPath());
          }
          catch (IOException e1)
          {
            e1.printStackTrace();
          }
        }
      }

    });

    // exit if cancel button hit
    wsform._CANCEL_BUTTON.addActionListener(new ActionListener()
    {

      public void actionPerformed(ActionEvent e)
      {
        System.exit(0);
      }

    });

    JFrame frame = new JFrame();
    frame.setTitle(TITLE);
    frame.setSize(530, 450);
    frame.setLocation(100, 100);
    frame.getContentPane().add(wsform);
    frame.setVisible(true);

    frame.addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent evt)
      {
        System.exit(0);
      }
    });

    showStep("Click button to continue");

    // wait for continue button
    lock.lock();
    cont.await();
    lock.unlock();

    // get user data
    destination = wsform._INSTALL_FOLDER.getText();
    if (wsform._INSTALL_OPTION.isSelected())
    {
View Full Code Here

            for (SymbolEntry e = (table = symbolTable)[hash & (table.length - 1)]; e != null; e = e.next) {
                if (hash == e.hash && name.equals(e.name)) {
                    return e.symbol;
                }
            }
            ReentrantLock lock;
            (lock = tableLock).lock();
            try {
                int potentialNewSize;
                if ((potentialNewSize = size + 1) > threshold) {
                    table = rehash();
                } else {
                    table = symbolTable;
                }
                int index;
                // try lookup again under lock
                for (SymbolEntry e = table[index = hash & (table.length - 1)]; e != null; e = e.next) {
                    if (hash == e.hash && name.equals(e.name)) {
                        return e.symbol;
                    }
                }
                String internedName;
                RubySymbol symbol = new RubySymbol(runtime, internedName = name.intern());
                table[index] = new SymbolEntry(hash, internedName, symbol, table[index]);
                size = potentialNewSize;
                // write-volatile
                symbolTable = table;
                return symbol;
            } finally {
                lock.unlock();
            }
        }
View Full Code Here

            for (SymbolEntry e = (table = symbolTable)[internedName.hashCode() & (table.length - 1)]; e != null; e = e.next) {
                if (internedName == e.name) {
                    return e.symbol;
                }
            }
            ReentrantLock lock;
            (lock = tableLock).lock();
            try {
                int potentialNewSize;
                if ((potentialNewSize = size + 1) > threshold) {
                    table = rehash();
                } else {
                    table = symbolTable;
                }
                int index;
                int hash;
                // try lookup again under lock
                for (SymbolEntry e = table[index = (hash = internedName.hashCode()) & (table.length - 1)]; e != null; e = e.next) {
                    if (internedName == e.name) {
                        return e.symbol;
                    }
                }
                RubySymbol symbol = new RubySymbol(runtime, internedName);
                table[index] = new SymbolEntry(hash, internedName, symbol, table[index]);
                size = potentialNewSize;
                // write-volatile
                symbolTable = table;
                return symbol;
            } finally {
                lock.unlock();
            }
        }
View Full Code Here

          "Please fix the configuration.");
    }
    AtomicBoolean txnFail = new AtomicBoolean(false);
    AtomicInteger callbacksReceived = new AtomicInteger(0);
    AtomicInteger callbacksExpected = new AtomicInteger(0);
    final Lock lock = new ReentrantLock();
    final Condition condition = lock.newCondition();
    /*
     * Callbacks can be reused per transaction, since they share the same
     * locks and conditions.
     */
    Callback<Object, Object> putSuccessCallback =
            new SuccessCallback<Object, Object>(
            lock, callbacksReceived, condition);
    Callback<Object, Object> putFailureCallback =
            new FailureCallback<Object, Object>(
            lock, callbacksReceived, txnFail, condition);

    Callback<Long, Long> incrementSuccessCallback =
            new SuccessCallback<Long, Long>(
            lock, callbacksReceived, condition);
    Callback<Long, Long> incrementFailureCallback =
            new FailureCallback<Long, Long>(
            lock, callbacksReceived, txnFail, condition);

    Status status = Status.READY;
    Channel channel = getChannel();
    int i = 0;
    try {
      txn = channel.getTransaction();
      txn.begin();
      for (; i < batchSize; i++) {
        Event event = channel.take();
        if (event == null) {
          status = Status.BACKOFF;
          if (i == 0) {
            sinkCounter.incrementBatchEmptyCount();
          } else {
            sinkCounter.incrementBatchUnderflowCount();
          }
          break;
        } else {
          serializer.setEvent(event);
          List<PutRequest> actions = serializer.getActions();
          List<AtomicIncrementRequest> increments = serializer.getIncrements();
          callbacksExpected.addAndGet(actions.size() + increments.size());

          for (PutRequest action : actions) {
            client.put(action).addCallbacks(putSuccessCallback, putFailureCallback);
          }
          for (AtomicIncrementRequest increment : increments) {
            client.atomicIncrement(increment).addCallbacks(
                    incrementSuccessCallback, incrementFailureCallback);
          }
        }
      }
    } catch (Throwable e) {
      this.handleTransactionFailure(txn);
      this.checkIfChannelExceptionAndThrow(e);
    }
    if (i == batchSize) {
      sinkCounter.incrementBatchCompleteCount();
    }
    sinkCounter.addToEventDrainAttemptCount(i);

    lock.lock();
    try {
      while ((callbacksReceived.get() < callbacksExpected.get())
              && !txnFail.get()) {
        try {
          if(!condition.await(timeout, TimeUnit.MILLISECONDS)){
            txnFail.set(true);
            logger.warn("HBase callbacks timed out. "
                    + "Transaction will be rolled back.");
          }
        } catch (Exception ex) {
          logger.error("Exception while waiting for callbacks from HBase.");
          this.handleTransactionFailure(txn);
          Throwables.propagate(ex);
        }
      }
    } finally {
      lock.unlock();
    }

    /*
     * At this point, either the txn has failed
     * or all callbacks received and txn is successful.
View Full Code Here

     * @throws InterruptedException
     */
    public void put(E e) throws InterruptedException {
        Importance i = (Importance) e;
        InternalQueue<E> internalQueue = getQueueForPriority(i.getPriority());
        final ReentrantLock lock = this.lock;
        lock.lockInterruptibly();
        try {
            try {
                while (internalQueue.remainingCapacity() == 0) {
                    internalQueue.getNotFullCond().await();
                }
            } catch (InterruptedException ie) {
                internalQueue.getNotFullCond().signal();
                throw ie;
            }

            internalQueue.offer(e);
            count++;

            notEmpty.signal();
        } finally {
            lock.unlock();
        }       
    }
View Full Code Here

     * @return true if element is added
     */
    public boolean offer(E e) {
        Importance i = (Importance) e;
        InternalQueue<E> internalQueue = getQueueForPriority(i.getPriority());
        final ReentrantLock lock = this.lock;
        lock.lock();
        try {
            if (internalQueue.remainingCapacity() > 0) {
                internalQueue.offer(e);
                count++;
                notEmpty.signal();
                return true;
            } else {
                return false;
            }
        } finally {
            lock.unlock();
        }
    }
View Full Code Here

TOP

Related Classes of java.util.concurrent.locks.ReentrantLock

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.