List of usage examples for java.util.concurrent.locks Lock unlock
void unlock();
From source file:org.openhab.binding.neeo.internal.handler.NeeoBrainHandler.java
/** * Disposes of the bridge by closing/removing the {@link #neeoBrainApi} and canceling/removing any pending * {@link #initializeTask()}//from w ww. j av a 2 s .c o m */ @Override public void dispose() { final Lock writerLock = stateLock.writeLock(); writerLock.lock(); try { final NeeoBrainApi api = neeoBrainApi; neeoBrainApi = null; NeeoUtil.cancel(initializationTask.getAndSet(null)); NeeoUtil.cancel(checkStatus.getAndSet(null)); if (forwardActionServlet != null) { forwardActionServlet = null; if (api != null) { try { api.deregisterForwardActions(); } catch (IOException e) { logger.debug("IOException occurred deregistering the forward actions: {}", e.getMessage(), e); } } if (servletPath != null) { httpService.unregister(servletPath); servletPath = null; } } NeeoUtil.close(api); } finally { writerLock.unlock(); } }
From source file:org.marketcetera.marketdata.core.manager.impl.MarketDataManagerImpl.java
@Override public void cancelMarketDataRequest(long inRequestId) { SLF4JLoggerProxy.debug(this, "Canceling request {}", inRequestId); Lock cancelLock = requestLockObject.writeLock(); try {//from w w w. j a v a 2 s . c om cancelLock.lockInterruptibly(); MarketDataRequestToken token = tokensByTokenId.remove(inRequestId); if (token != null) { for (MarketDataProvider provider : providersByToken.removeAll(token)) { SLF4JLoggerProxy.debug(this, "Canceling request {} with {}", inRequestId, provider); provider.cancelMarketDataRequest(token); } } } catch (InterruptedException ignored) { } finally { cancelLock.unlock(); } }
From source file:org.marketcetera.marketdata.core.provider.AbstractMarketDataProvider.java
@Override public Event getSnapshot(Instrument inInstrument, Content inContent) { Lock snapshotLock = marketdataLock.readLock(); try {/*from www.ja va2 s. c om*/ snapshotLock.lockInterruptibly(); MarketdataCacheElement cachedData = cachedMarketdata.get(inInstrument); if (cachedData != null) { return cachedData.getSnapshot(inContent); } return null; } catch (InterruptedException e) { org.marketcetera.marketdata.core.Messages.UNABLE_TO_ACQUIRE_LOCK.error(this); stop(); throw new MarketDataRequestFailed(e); } finally { snapshotLock.unlock(); } }
From source file:org.mule.util.queue.DualRandomAccessFileQueueStoreDelegate.java
private void switchWriteFileIfFull() { if (writeFile.getLength() >= MAXIMUM_QUEUE_FILE_SIZE_IN_BYTES) { Lock lock = filesLock.writeLock(); lock.lock();//from w w w.ja v a2 s . c o m try { if (writeFile.getLength() >= MAXIMUM_QUEUE_FILE_SIZE_IN_BYTES) { if (randomAccessFileQueueStore1.getLength() >= MAXIMUM_QUEUE_FILE_SIZE_IN_BYTES && randomAccessFileQueueStore2.getLength() >= MAXIMUM_QUEUE_FILE_SIZE_IN_BYTES) { return; } if (logger.isDebugEnabled()) { logger.debug( "switching write file. Random 1 size: " + randomAccessFileQueueStore1.getLength() + " , Random 2 size: " + randomAccessFileQueueStore2.getLength()); } writeFile = (writeFile == randomAccessFileQueueStore1 ? randomAccessFileQueueStore2 : randomAccessFileQueueStore1); queueControlDataFile.writeControlData(writeFile.getFile(), readFile.getFile()); } } finally { lock.unlock(); } } }
From source file:com.cloudera.oryx.als.serving.ServerRecommender.java
private float[] buildAnonymousUserFeatures(String[] itemIDs, float[] values) throws NotReadyException, NoSuchItemException { Preconditions.checkArgument(values == null || values.length == itemIDs.length, "Number of values doesn't match number of items"); Generation generation = getCurrentGeneration(); LongObjectMap<float[]> Y = generation.getY(); Solver ytySolver = generation.getYTYSolver(); if (ytySolver == null) { throw new NotReadyException(); }/*from w ww . j a va2 s . c o m*/ float[] anonymousUserFeatures = null; Lock yLock = generation.getYLock().readLock(); boolean anyItemIDFound = false; for (int j = 0; j < itemIDs.length; j++) { String itemID = itemIDs[j]; float[] itemFeatures; yLock.lock(); try { itemFeatures = Y.get(StringLongMapping.toLong(itemID)); } finally { yLock.unlock(); } if (itemFeatures == null) { continue; } anyItemIDFound = true; double[] userFoldIn = ytySolver.solveFToD(itemFeatures); if (anonymousUserFeatures == null) { anonymousUserFeatures = new float[userFoldIn.length]; } double signedFoldInWeight = foldInWeight(0.0, values == null ? 1.0f : values[j]); if (signedFoldInWeight != 0.0) { for (int i = 0; i < anonymousUserFeatures.length; i++) { anonymousUserFeatures[i] += (float) (signedFoldInWeight * userFoldIn[i]); } } } if (!anyItemIDFound) { throw new NoSuchItemException(Arrays.toString(itemIDs)); } return anonymousUserFeatures; }
From source file:org.marketcetera.marketdata.core.provider.AbstractMarketDataProvider.java
/** * Creates a link between the given symbol and the given instrument. * * @param inSymbol a <code>String</code> value * @param inInstrument an <code>Instrument</code> value *///from w w w . j a va2 s.c om protected void addSymbolMapping(String inSymbol, Instrument inInstrument) { SLF4JLoggerProxy.debug(this, "Adding symbol mapping: {} -> {}", inSymbol, inInstrument); Lock symbolMappingLock = marketdataLock.writeLock(); try { symbolMappingLock.lockInterruptibly(); instrumentsBySymbol.put(inSymbol, inInstrument); Collection<MarketDataRequestToken> tokens = requestsBySymbol.get(inSymbol); for (MarketDataRequestToken token : tokens) { requestsByInstrument.put(inInstrument, token); } } catch (InterruptedException e) { org.marketcetera.marketdata.core.Messages.UNABLE_TO_ACQUIRE_LOCK.error(this); stop(); } finally { symbolMappingLock.unlock(); } }
From source file:org.pentaho.platform.plugin.action.olap.impl.OlapServiceImpl.java
public List<IOlapService.Catalog> getCatalogs(IPentahoSession session) throws IOlapServiceException { // Make sure the cache is initialized. initCache(session);/*from ww w . j a v a 2 s .co m*/ final List<Catalog> cache = getCache(session); final Lock readLock = cacheLock.readLock(); try { readLock.lock(); final List<IOlapService.Catalog> catalogs = new ArrayList<IOlapService.Catalog>(); for (Catalog catalog : cache) { if (hasAccess(catalog.name, EnumSet.of(RepositoryFilePermission.READ), session)) { catalogs.add(catalog); } } // Do not leak the cache list. // Do not allow modifications on the list. return Collections.unmodifiableList(new ArrayList<IOlapService.Catalog>(cache)); } finally { readLock.unlock(); } }
From source file:com.funambol.pushlistener.service.taskexecutor.ScheduledTaskExecutor.java
/** * Plans an execution of the given TaskWrapper (the execution will be performed as soon * as a thread is available and the delay expires). * <p>IMPORTANT NOTE: the caller must lock the task before calling this method * using getHandlingTaskLock to obtain a lock instance. * @return true if the task execution has been planned to be performed as soon as * possible, false otherwise//from w w w .j a v a2 s . c o m * (the same task or another equal task is waiting for its execution or * is already running) * @param newTask the task to execute * @param delay the delay in the execution */ private boolean submitTaskWrapper(TaskWrapper newTask, long delay) { if (newTask == null) { throw new IllegalArgumentException("Task must be not null"); } ScheduledFuture future = null; TaskWrapper task = null; // // The caller must lock the task // synchronized (taskFutures) { future = (ScheduledFuture) taskFutures.get(newTask); task = (TaskWrapper) taskFutures.getKey(future); } // // Task null means that in taskFutures there is not the task yet (first // execution ?) // if (task == null) { task = newTask; } else { // // There is already an equals task in the taskFutures map. We try // to force queue a new execution // boolean queued = false; queued = task.queueNewExecution(); if (queued) { if (log.isTraceEnabled()) { log.trace("Execution of '" + task + "' queued"); } return false; } } // // We use the execution lock to avoid the task execution before putting // it in the taskFutures map. // See TaskWrapper.execute // Lock taskExecutionLock = new ReentrantLock(); taskExecutionLock.lock(); try { task.setExecutionLock(taskExecutionLock); future = schedule(task, delay, TimeUnit.MILLISECONDS); synchronized (taskFutures) { taskFutures.put(task, future); } } finally { taskExecutionLock.unlock(); } return true; }
From source file:com.epam.jdi.uitests.web.selenium.driver.SeleniumDriverFactory.java
public WebDriver getDriver(String driverName) { if (!drivers.keys().contains(driverName)) if (drivers.isEmpty()) registerDriver("DEFAULT DRIVER", getDefaultDriver()); else// w ww . j av a 2 s .c o m throw exception("Can't find driver with name '%s'", driverName); try { Lock lock = new ReentrantLock(); lock.lock(); if (runDrivers.get() == null || !runDrivers.get().keys().contains(driverName)) { MapArray<String, WebDriver> rDrivers = runDrivers.get(); if (rDrivers == null) rDrivers = new MapArray<>(); WebDriver resultDriver = webDriverSettings.apply(drivers.get(driverName).get()); if (resultDriver == null) throw exception("Can't get WebDriver '%s'. This Driver name not registered", driverName); rDrivers.add(driverName, resultDriver); runDrivers.set(rDrivers); } WebDriver result = runDrivers.get().get(driverName); if (result.toString().contains("(null)")) { result = webDriverSettings.apply(drivers.get(driverName).get()); runDrivers.get().update(driverName, result); } lock.unlock(); return result; } catch (Exception ex) { throw exception("Can't get driver; Thread: " + currentThread().getId() + LINE_BREAK + format("Drivers: %s; Run: %s", drivers, runDrivers) + "Exception: " + ex.getMessage()); } }
From source file:org.geotools.gce.imagemosaic.catalog.GTDataStoreGranuleCatalog.java
@Override public SimpleFeatureCollection getGranules(Query q) throws IOException { Utilities.ensureNonNull("query", q); q = mergeHints(q);/*from w ww .ja va2 s .com*/ String typeName = q.getTypeName(); final Lock lock = rwLock.readLock(); try { lock.lock(); checkStore(); // // Load tiles informations, especially the bounds, which will be // reused // final SimpleFeatureSource featureSource = tileIndexStore.getFeatureSource(typeName); if (featureSource == null) { throw new NullPointerException( "The provided SimpleFeatureSource is null, it's impossible to create an index!"); } return featureSource.getFeatures(q); } catch (Throwable e) { final IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } finally { lock.unlock(); } }