List of usage examples for java.util.concurrent.locks ReentrantLock ReentrantLock
public ReentrantLock()
From source file:org.proninyaroslav.libretorrent.services.TorrentTaskService.java
public TorrentTaskService() { exec = Executors.newSingleThreadExecutor(); sync = new ReentrantLock(); needsUpdateNotify = new AtomicBoolean(false); }
From source file:com.hartveld.commons.test.swing.AbstractSwingFrameTest.java
private void createAndAcquireLock() throws RuntimeException { LOG.trace("Creating and acquiring lock ..."); checkIsNotEDT();//from ww w .j av a 2 s .c o m lock = new ReentrantLock(); try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { LOG.trace("Attempting to acquire lock ..."); if (!lock.tryLock()) { throw new RuntimeException("Failed to acquire UI lock"); } } }); } catch (InterruptedException | InvocationTargetException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
From source file:org.apache.openjpa.kernel.QueryImpl.java
/** * Construct a query managed by the given broker. *///from w ww. jav a 2 s. co m public QueryImpl(Broker broker, String language, StoreQuery storeQuery) { _broker = (BrokerImpl) broker; _language = language; _storeQuery = storeQuery; _fc = (FetchConfiguration) broker.getFetchConfiguration().clone(); _log = broker.getConfiguration().getLog(OpenJPAConfiguration.LOG_QUERY); _storeQuery.setContext(this); _printParameters = _broker.getPrintParameters(); if (_broker != null && _broker.getMultithreaded()) _lock = new ReentrantLock(); }
From source file:org.rifidi.designer.services.core.world.WorldServiceImpl.java
@Override public void sceneDataChanged(SceneData sceneData) { logger.debug("starting threads"); this.sceneData = sceneData; lock = new ReentrantLock(); // create the render thread renderThread = new RenderThread(lock, display, glCanvas, sceneData, messagingService); // create the update thread if (updateThread != null) glCanvas.removeKeyListener(updateThread); updateThread = new UpdateThread(lock, sceneData, repeatedActions, fieldService, cameraService); updateThread.setPaused(true);/*from w w w . j ava 2s . c o m*/ glCanvas.addKeyListener(updateThread); // start the render and update threads updateThread.start(); renderThread.start(); worldState = WorldStates.Paused; }
From source file:com.cloudbees.hudson.plugins.folder.computed.ComputedFolder.java
/** * {@inheritDoc}/*from w w w. jav a 2 s .c om*/ */ @Override protected final void init() { super.init(); if (orphanedItemStrategy == null) { orphanedItemStrategy = new DefaultOrphanedItemStrategy(true, "0", "0"); } if (triggers == null) { triggers = new DescribableList<Trigger<?>, TriggerDescriptor>(this); } else { triggers.setOwner(this); } for (Trigger t : triggers) { t.start(this, Items.currentlyUpdatingByXml()); } synchronized (this) { computation = createComputation(null); } currentObservationsLock = new ReentrantLock(); currentObservationsChanged = currentObservationsLock.newCondition(); currentObservations = new HashSet<>(); }
From source file:org.eclipse.gyrex.persistence.internal.storage.RepositoryRegistry.java
private Lock getOrCreateRepositoryLock(final String repositoryId) { Lock lock = locksByRepositoryId.get(repositoryId); if (lock == null) { final Lock newLock = new ReentrantLock(); lock = locksByRepositoryId.putIfAbsent(repositoryId, newLock); if (lock == null) { // put succeeded, use new value lock = newLock;/*from w w w. jav a2 s. com*/ } } return lock; }
From source file:org.springframework.integration.aggregator.AggregatorTests.java
@Test public void testCustomAggPerf() throws InterruptedException, ExecutionException, TimeoutException { class CustomHandler extends AbstractMessageHandler { // custom aggregator, only handles a single correlation private final ReentrantLock lock = new ReentrantLock(); private final Collection<Message<?>> messages = new ArrayList<Message<?>>(60000); private final MessageChannel outputChannel; private CustomHandler(MessageChannel outputChannel) { this.outputChannel = outputChannel; }/* w w w. jav a 2 s . co m*/ @Override public void handleMessageInternal(Message<?> requestMessage) { lock.lock(); try { this.messages.add(requestMessage); if (this.messages.size() == 60000) { List<Object> payloads = new ArrayList<Object>(this.messages.size()); for (Message<?> message : this.messages) { payloads.add(message.getPayload()); } this.messages.clear(); outputChannel.send(getMessageBuilderFactory().withPayload(payloads) .copyHeaders(requestMessage.getHeaders()).build()); } } finally { lock.unlock(); } } } DirectChannel outputChannel = new DirectChannel(); CustomHandler handler = new CustomHandler(outputChannel); final CompletableFuture<Collection<?>> resultFuture = new CompletableFuture<>(); outputChannel.subscribe(message -> { Collection<?> payload = (Collection<?>) message.getPayload(); logger.warn("Received " + payload.size()); resultFuture.complete(payload); }); Message<?> message = new GenericMessage<String>("foo"); StopWatch stopwatch = new StopWatch(); stopwatch.start(); for (int i = 0; i < 120000; i++) { if (i % 10000 == 0) { stopwatch.stop(); logger.warn("Sent " + i + " in " + stopwatch.getTotalTimeSeconds() + " (10k in " + stopwatch.getLastTaskTimeMillis() + "ms)"); stopwatch.start(); } handler.handleMessage(message); } stopwatch.stop(); logger.warn("Sent " + 120000 + " in " + stopwatch.getTotalTimeSeconds() + " (10k in " + stopwatch.getLastTaskTimeMillis() + "ms)"); Collection<?> result = resultFuture.get(10, TimeUnit.SECONDS); assertNotNull(result); assertEquals(60000, result.size()); }
From source file:org.openhab.binding.tesla.internal.handler.TeslaHandler.java
@Override public void initialize() { logger.trace("Initializing the Tesla handler for {}", this.getStorageKey()); updateStatus(ThingStatus.UNKNOWN); lock = new ReentrantLock(); lock.lock();//from w w w .j a va 2 s. com try { if (connectJob == null || connectJob.isCancelled()) { connectJob = scheduler.scheduleWithFixedDelay(connectRunnable, 0, CONNECT_RETRY_INTERVAL, TimeUnit.MILLISECONDS); } Map<Object, Rate> channels = new HashMap<>(); channels.put(DATA_THROTTLE, new Rate(1, 1, TimeUnit.SECONDS)); channels.put(COMMAND_THROTTLE, new Rate(20, 1, TimeUnit.MINUTES)); Rate firstRate = new Rate(20, 1, TimeUnit.MINUTES); Rate secondRate = new Rate(200, 10, TimeUnit.MINUTES); stateThrottler = new QueueChannelThrottler(firstRate, scheduler, channels); stateThrottler.addRate(secondRate); if (fastStateJob == null || fastStateJob.isCancelled()) { fastStateJob = scheduler.scheduleWithFixedDelay(fastStateRunnable, 0, FAST_STATUS_REFRESH_INTERVAL, TimeUnit.MILLISECONDS); } if (slowStateJob == null || slowStateJob.isCancelled()) { slowStateJob = scheduler.scheduleWithFixedDelay(slowStateRunnable, 0, SLOW_STATUS_REFRESH_INTERVAL, TimeUnit.MILLISECONDS); } } finally { lock.unlock(); } }
From source file:com.lonepulse.zombielink.processor.AsyncEndpointTest.java
/** * <p>Tests a failed asynchronous request where the implementation of the * {@link AsyncHandler#onFailure(HttpResponse)} callback throws an exception.</p> * //from w ww . j ava 2 s .c o m * @since 1.3.0 */ @Test public final void testAsyncFailureCallbackError() throws InterruptedException { String subpath = "/failurecallbackerror"; stubFor(get(urlEqualTo(subpath)).willReturn(aResponse().withStatus(404))); final Lock lock = new ReentrantLock(); final Condition condition = lock.newCondition(); asyncEndpoint.asyncFailureCallbackError(new AsyncHandler<String>() { @Override public void onSuccess(HttpResponse httpResponse, String e) { } @Override public void onFailure(HttpResponse httpResponse) { try { throw new IllegalStateException(); } finally { lock.lock(); condition.signal(); lock.unlock(); } } }); lock.lock(); condition.await(); lock.unlock(); verify(getRequestedFor(urlEqualTo(subpath))); successScenario(); //verify that the asynchronous request executor has survived the exception }
From source file:org.nuxeo.ecm.platform.web.common.requestcontroller.filter.NuxeoRequestControllerFilter.java
/** * Synchronizes the HttpSession./* www . java 2 s . co m*/ * <p> * Uses a {@link Lock} object in the HttpSession and locks it. If HttpSession is not created, exits without locking * anything. */ public static boolean simpleSyncOnSession(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session == null) { if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request, "HttpSession does not exist, this request won't be synched")); } return false; } if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request, "Trying to sync on session ")); } if (request.getAttribute(SYNCED_REQUEST_FLAG) != null) { if (log.isWarnEnabled()) { log.warn(doFormatLogMessage(request, "Request has already be synced, filter is reentrant, exiting without locking")); } return false; } Lock lock = (Lock) session.getAttribute(SESSION_LOCK_KEY); if (lock == null) { lock = new ReentrantLock(); session.setAttribute(SESSION_LOCK_KEY, lock); } boolean locked = false; try { locked = lock.tryLock(LOCK_TIMOUT_S, TimeUnit.SECONDS); } catch (InterruptedException e) { log.error(doFormatLogMessage(request, "Unable to acquire lock for Session sync"), e); return false; } if (locked) { request.setAttribute(SYNCED_REQUEST_FLAG, true); if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request, "Request synced on session")); } } else { if (log.isDebugEnabled()) { log.debug(doFormatLogMessage(request, "Sync timeout")); } } return locked; }