Package java.util.concurrent.locks

Examples of java.util.concurrent.locks.Lock


        long mills1 = System.currentTimeMillis();
        long ops = 0L;
        long miss = 0L;
        int iocontention = 0;

        final Lock readLock = rwlock.readLock();
        final Lock writeLock = rwlock.writeLock();

        final int start = thrdnum * round;
        final int limit = start + round - 1;
        for(int nth = start, i = 0; !_stop; nth = (nth < limit) ? nth + 1 : start, i++) {
            final long key;
View Full Code Here


        long mills1 = System.currentTimeMillis();
        long ops = 0L;
        long miss = 0L;
        int iocontention = 0;

        final Lock readLock = rwlock.readLock();
        final Lock writeLock = rwlock.writeLock();

        final int start = thrdnum * round;
        final int limit = start + round - 1;
        for(int nth = start, i = 0; !_stop; nth = (nth < limit) ? nth + 1 : start, i++) {
            final long key;
View Full Code Here

    public void run()
    {
       try
       {
          Lock rlock = lock_.readLock();
          Lock wlock;
          if (!rlock.tryLock(0, TimeUnit.MILLISECONDS))
          {
             String str = caseNum + "-" + name + "-RL-0";
             postLockingResult(str);
             notifyBeforeFinish.countDown();
            if (beforeUpgrateWait != null) beforeUpgrateWait.await(10, TimeUnit.SECONDS);
            return;
          }
          // OK, read lock obtained, sleep and upgrade it later.
          notifyBeforeSecondOp.countDown();
          if (beforeUpgrateWait != null) beforeUpgrateWait.await(10, TimeUnit.SECONDS);
          String str = caseNum + "-" + name + "-UL-";
          if ((wlock = lock_.upgradeLockAttempt(0)) == null)
          {
             str += "0";
          }
          else
          {
             str += "1";
          }
          postLockingResult(str);
          // Sleep again and then release the lock.
          TestingUtil.sleepThread(SLEEP_MSECS);
          if (wlock != null)
          {
             wlock.unlock();
          }
          rlock.unlock();
          notifyBeforeFinish.countDown();
          if (beforeFinishWait != null) beforeFinishWait.await(10, TimeUnit.SECONDS);
       }
View Full Code Here

    if ( trace ) log.trace( "Opening IndexReader for directoryProviders: " + length );

    for (int index = 0; index < length; index++) {
      DirectoryProvider directoryProvider = directoryProviders[index];
      IndexReader reader;
      Lock directoryProviderLock = perDirectoryProviderManipulationLocks.get( directoryProvider );
      if ( trace ) log.trace( "Opening IndexReader from " + directoryProvider.getDirectory().toString() );
      directoryProviderLock.lock(); //needed for same problem as the double-checked locking
      try {
        reader = activeSearchIndexReaders.get( directoryProvider );
      }
      finally {
        directoryProviderLock.unlock();
      }
      if ( reader == null ) {
        if ( trace )
          log.trace( "No shared IndexReader, opening a new one: " + directoryProvider.getDirectory().toString() );
        reader = replaceActiveReader( null, directoryProviderLock, directoryProvider, readers );
      }
      else {
        boolean isCurrent;
        try {
          isCurrent = reader.isCurrent();
        }
        catch (IOException e) {
          throw new SearchException( "Unable to read current status of Lucene IndexReader", e );
        }
        if ( !isCurrent ) {
          if ( trace )
            log.trace( "Out of date shared IndexReader found, opening a new one: " + directoryProvider.getDirectory().toString() );
          IndexReader outOfDateReader = reader;
          reader = replaceActiveReader( outOfDateReader, directoryProviderLock, directoryProvider, readers );
        }
        else {
          if ( trace )
            log.trace( "Valid shared IndexReader: " + directoryProvider.getDirectory().toString() );
          directoryProviderLock.lock();
          try {
            //read the latest active one, the current one could be out of date and closed already
            //the latest active is guaranteed to be active because it's protected by the dp lock
            reader = activeSearchIndexReaders.get( directoryProvider );
            semaphoreIndexReaderLock.lock();
            try {
              SharedReaderProvider.ReaderData readerData = searchIndexReaderSemaphores.get( reader );
              //TODO if readerData is null????
              readerData.semaphore++;
              searchIndexReaderSemaphores.put( reader, readerData ); //not necessary
              if ( trace ) log.trace( "Semaphore increased: " + readerData.semaphore + " for " + reader );
            }
            finally {
              semaphoreIndexReaderLock.unlock();
            }
          }
          finally {
            directoryProviderLock.unlock();
          }
        }
      }
      readers[index] = reader;
    }
View Full Code Here

        //TODO should we try to close?
        continue;
      }

      //acquire the locks in the same order as everywhere else
      Lock directoryProviderLock = perDirectoryProviderManipulationLocks.get( readerData.provider );
      boolean closeReader = false;
      directoryProviderLock.lock();
      try {
        boolean isActive;
        isActive = activeSearchIndexReaders.get( readerData.provider ) == subReader;
        if ( trace ) log.trace( "Indexreader not active: " + subReader );
        semaphoreIndexReaderLock.lock();
        try {
          readerData = searchIndexReaderSemaphores.get( subReader );
          if ( readerData == null ) {
            log.error( "Trying to close a Lucene IndexReader not present: " + subReader.directory().toString() );
            //TODO should we try to close?
            continue;
          }
          readerData.semaphore--;
          if ( trace ) log.trace( "Semaphore decreased to: " + readerData.semaphore + " for " + subReader );
          if ( readerData.semaphore < 0 )
            log.error( "Semaphore negative: " + subReader.directory().toString() );
          if ( ( !isActive ) && readerData.semaphore == 0 ) {
            searchIndexReaderSemaphores.remove( subReader );
            closeReader = true;
          }
          else {
            closeReader = false;
          }
        }
        finally {
          semaphoreIndexReaderLock.unlock();
        }
      }
      finally {
        directoryProviderLock.unlock();
      }

      if ( closeReader ) {
        if ( trace ) log.trace( "Closing IndexReader: " + subReader );
        try {
View Full Code Here

        }
    }

    public static class NoCleanUpRemoteProcess implements Action<WorkerProcessContext>, Serializable {
        public void execute(WorkerProcessContext workerProcessContext) {
            final Lock lock = new ReentrantLock();
            lock.lock();
            new Thread(new Runnable() {
                public void run() {
                    lock.lock();
                }
            }).start();

            TestListenerInterface sender = workerProcessContext.getServerConnection().addOutgoing(
                    TestListenerInterface.class);
View Full Code Here

    public void testSchedule() throws Exception {
        workqueue = new AutomaticWorkQueueImpl(UNBOUNDED_MAX_QUEUE_SIZE, INITIAL_SIZE,
                                               UNBOUNDED_HIGH_WATER_MARK,
                                               UNBOUNDED_LOW_WATER_MARK,
                                               DEFAULT_DEQUEUE_TIMEOUT);
        final Lock runLock = new ReentrantLock();
        final Condition runCondition = runLock.newCondition();
        long start = System.currentTimeMillis();
        Runnable doNothing = new Runnable() {
            public void run() {
                runLock.lock();
                try {
                    runCondition.signal();
                } finally {
                    runLock.unlock();
                }
            }
        };
       
        workqueue.schedule(doNothing, 5000);
       
        runLock.lock();
        try {
            runCondition.await();
        } finally {
            runLock.unlock();
        }
       
        assertTrue("expected delay",
                   System.currentTimeMillis() - start >= 4950);
    }
View Full Code Here

  @SuppressWarnings("unused")
  private void asyncSetState(final Collection<INews> news, final State state, final boolean affectEquivalentNews, final boolean force) throws PersistenceException {
    if (news.isEmpty())
      return;
    final NewsEventRunnable eventRunnable = new NewsEventRunnable();;
    final Lock setStateLock = new ReentrantLock();
    setStateLock.lock();
    final Condition condition = setStateLock.newCondition();
    fExecutorService.execute(new Runnable() {
      public void run() {
        Set<INews> changedNews = null;
        try {
          fWriteLock.lock();
          setStateLock.lock();

          if (affectEquivalentNews) {
            /*
             * Give extra 25% size to take into account news that have same guid or
             * link.
             */
            int capacity = news.size() + (news.size() / 4);
            changedNews = new HashSet<INews>(capacity);
            for (INews newsItem : news) {
              if (newsItem.getId() == null)
                throw new IllegalArgumentException("newsItem was never saved to the database"); //$NON-NLS-1$

              List<INews> equivalentNews;

              if (newsItem.getGuid() != null) {
                equivalentNews = getNewsFromGuid(newsItem, true);
                if (equivalentNews.isEmpty()) {
                  throw createIllegalException("No news were found with guid: " + //$NON-NLS-1$
                      newsItem.getGuid().getValue(), newsItem);
                }
              } else if (newsItem.getLinkAsText() != null) {
                equivalentNews = getNewsFromLink(newsItem, true);
                if (equivalentNews.isEmpty()) {
                  throw createIllegalException("No news were found with link: " + //$NON-NLS-1$
                      newsItem.getLinkAsText(), newsItem);
                }
              } else
                equivalentNews = Collections.singletonList(newsItem);

              changedNews.addAll(setState(equivalentNews, state, force));
            }
          } else {
            changedNews = setState(news, state, force);
          }
          for (INews changedNewsItem : changedNews) {
            //TODO Investigate why we add the news twice to the event runnable
            //(we do the same in the finally block). This is harmless but
            //wasteful. Also we should not release the news locks before firing
            //the events.
            ((News) changedNewsItem).acquireReadLockSpecial();
            eventRunnable.addCheckedUpdateEvent(createSaveEventTemplate(changedNewsItem));
          }
          condition.signal();
          setStateLock.unlock();
          save(changedNews);
          fDb.commit();
        } catch (Db4oException e) {
          throw new PersistenceException(e);
        } finally {
          if (changedNews != null) {
            for (INews changedNewsItem : changedNews) {
              ((News) changedNewsItem).releaseReadLockSpecial();
              eventRunnable.addCheckedUpdateEvent(createSaveEventTemplate(changedNewsItem));
            }
          }
          DBHelper.cleanUpEvents();
          fWriteLock.unlock();
        }
      }
    });
    try {
      condition.awaitUninterruptibly();
    } finally {
      setStateLock.unlock();
    }
    eventRunnable.run();
  }
View Full Code Here

        // TODO: manage lock per method and read or write lock !
        // for now, use only write lock

        // acquire lock
        Lock writeLock = this.lock.writeLock();
        writeLock.lock();

        try {
            value = m.invoke(bean, localCallRequest.getMethodArgs());
        } catch (IllegalArgumentException e) {
            ejbResponse.setRPCException(new RPCException(e));
            if (enabledEvent) {
                getEventDispatcher().dispatch(new EventBeanInvocationError(methodEventProviderId, number, e));
            }
        } catch (IllegalAccessException e) {
            ejbResponse.setRPCException(new RPCException(e));
            if (enabledEvent) {
                getEventDispatcher().dispatch(new EventBeanInvocationError(methodEventProviderId, number, e));
            }
        } catch (InvocationTargetException e) {
            Throwable cause = e.getCause();
            RPCException rpcException = new RPCException(cause);
            // ApplicationException ?
            ApplicationException applicationException = getBeanInfo().getApplicationExceptions().get(cause.getClass().getName());
            if (applicationException != null) {
                rpcException.setApplicationException();
            }
            ejbResponse.setRPCException(rpcException);
            if (enabledEvent) {
                getEventDispatcher().dispatch(new EventBeanInvocationError(methodEventProviderId, number, e));
            }
        } finally {
            if (enabledEvent) {
                getEventDispatcher().dispatch(new EventBeanInvocationEnd(methodEventProviderId, number, value));
                // Restore previous ID
                if (getCurrentInvocationID() != null) {
                    getCurrentInvocationID().setAuditID(previousID);
                }
            }

            Thread.currentThread().setContextClassLoader(oldClassLoader);
            getInvokedBusinessInterfaceNameThreadLocal().set(oldInvokedBusinessInterface);
            getOperationStateThreadLocal().set(oldState);

            // push back into the pool
            try {
                getPool().release(bean);
            } catch (PoolException e) {
                ejbResponse.setRPCException(new RPCException("cannot release bean", e));
            }
            // release lock
            writeLock.unlock();
        }
        ejbResponse.setValue(value);
        return ejbResponse;

    }
View Full Code Here

      if (existing != null)
      {
         session = existing;
      }
     
      Lock lock = session.getLock();

      if (!lock.tryLock())
      {
         throw new java.rmi.RemoteException("Concurent calls on session object.");
      }
     
      try
      {
         boolean isStateIdentical = session.setState(state);
        
         if (!isStateIdentical)
         {
            Object[] args = { appName, session };
           
            this.partition.callMethodOnCluster(this.sessionStateIdentifier, "_setState", args, SET_STATE_TYPES, true);
         }
      }
      catch (Exception e)
      {
         this.log.error("operation failed", e);
      }
      finally
      {
         lock.unlock();
      }
   }
View Full Code Here

TOP

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

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.