List of usage examples for java.util.concurrent.locks Lock unlock
void unlock();
From source file:org.cyberjos.jcconf2016.node.HazelcastHelper.java
/** * Sets the given node to be the master node. * * @param cloudNode the node to become master * @return {@code true} if the given node becomes the master node * successfully/* w w w . j av a 2 s . c o m*/ * @throws NullPointerException if the given node is {@code null} */ public synchronized boolean setMaster(final CloudNode cloudNode) { Objects.requireNonNull(cloudNode, "The given cloud node must not be null."); final Lock lock = hazelcastHolder.getInstance().getLock("my-distributed-lock"); lock.lock(); try { final String nodeName = cloudNode.getName(); final Optional<NodeRecord> optional = this.getMasterNodeRecord(); logger.info("[{}] Ensure the master node: {}", nodeName, optional.orElse(null)); if (optional.isPresent()) { final NodeRecord masterRecord = optional.get(); final long count = hazelcastHolder.getInstance().getCluster().getMembers().stream() .filter(member -> StringUtils.equals(masterRecord.getMemberId(), member.getUuid())).count(); if (count != 0) { logger.warn("[{}] The master node has already existed: {}", nodeName, masterRecord); return false; } this.unregisterNode(masterRecord.getNodeName()); } final NodeRecord newMasterRecord = HazelcastHelper.<String, NodeRecord>getMap(ACTIVE_NODES) .get(nodeName); HazelcastHelper.getAtomicReference(MASTER_NODE).set(newMasterRecord); logger.info("[{}] This node becomes the new master node: {}", nodeName, newMasterRecord); if (WORKING_MODE) { this.runProducer(cloudNode); } } finally { lock.unlock(); } return true; }
From source file:com.thoughtworks.studios.journey.JourneyService.java
/** * API for reindex journeys.//from ww w.j av a 2 s. c o m * * @param ns namespace under operation * @return 200 response */ @POST @Produces(MediaType.TEXT_PLAIN) @Path("/{ns}/reindex") public Response reindex(@PathParam("ns") String ns) { Lock writingLock = getWritingLock(ns); writingLock.lock(); try { Application app = new Application(graphDB, ns); try (Transaction tx = graphDB.beginTx()) { app.journeys().tearDownLegacyIndex(); tx.success(); } ArrayList<Long> ids = new ArrayList<>(); try (Transaction tx = graphDB.beginTx()) { ResourceIterator<Node> journeys = graphDB.findNodes(app.journeys().getLabel()); while (journeys.hasNext()) { ids.add(journeys.next().getId()); } tx.success(); } try (BatchTransaction tx = new BatchTransaction(graphDB, 100)) { for (Long id : ids) { Node journey = graphDB.getNodeById(id); app.journeys().reindex(journey); tx.increment(); } } } finally { writingLock.unlock(); } return Response.status(Response.Status.OK).build(); }
From source file:org.apache.bookkeeper.bookie.EntryLogManagerForEntryLogPerLedger.java
@Override public void setCurrentLogForLedgerAndAddToRotate(long ledgerId, BufferedLogChannel logChannel) throws IOException { Lock lock = getLock(ledgerId); lock.lock();/* w w w. ja v a2 s .c o m*/ try { BufferedLogChannel hasToRotateLogChannel = getCurrentLogForLedger(ledgerId); boolean newLedgerInEntryLogMapCache = (hasToRotateLogChannel == null); logChannel.setLedgerIdAssigned(ledgerId); BufferedLogChannelWithDirInfo logChannelWithDirInfo = new BufferedLogChannelWithDirInfo(logChannel); ledgerIdEntryLogMap.get(ledgerId).setEntryLogWithDirInfo(logChannelWithDirInfo); entryLogsPerLedgerCounter.openNewEntryLogForLedger(ledgerId, newLedgerInEntryLogMapCache); replicaOfCurrentLogChannels.put(logChannel.getLogId(), logChannelWithDirInfo); if (hasToRotateLogChannel != null) { replicaOfCurrentLogChannels.remove(hasToRotateLogChannel.getLogId()); rotatedLogChannels.add(hasToRotateLogChannel); } } catch (Exception e) { log.error("Received unexpected exception while fetching entry from map for ledger: " + ledgerId, e); throw new IOException("Received unexpected exception while fetching entry from map", e); } finally { lock.unlock(); } }
From source file:jp.aegif.nemaki.cmis.service.impl.ObjectServiceImpl.java
@Override public void deleteContentStream(CallContext callContext, String repositoryId, Holder<String> objectId, Holder<String> changeToken, ExtensionsData extension) { exceptionService.invalidArgumentRequiredHolderString("objectId", objectId); Lock lock = threadLockService.getWriteLock(repositoryId, objectId.getValue()); try {/*from w w w.j a v a2 s .c o m*/ lock.lock(); // ////////////////// // Exception // ////////////////// Document document = contentService.getDocument(repositoryId, objectId.getValue()); exceptionService.objectNotFound(DomainType.OBJECT, document, document.getId()); exceptionService.constraintContentStreamRequired(repositoryId, document); // ////////////////// // Body of the method // ////////////////// contentService.deleteContentStream(callContext, repositoryId, objectId); nemakiCachePool.get(repositoryId).removeCmisCache(objectId.getValue()); } finally { lock.unlock(); } }
From source file:jp.aegif.nemaki.cmis.service.impl.PolicyServiceImpl.java
@Override public void applyPolicy(CallContext callContext, String repositoryId, String policyId, String objectId, ExtensionsData extension) {//from w ww . j a v a 2 s. c om exceptionService.invalidArgumentRequiredString("objectId", objectId); exceptionService.invalidArgumentRequiredString("policyId", policyId); Lock objectLock = threadLockService.getWriteLock(repositoryId, objectId); Lock policyLock = threadLockService.getReadLock(repositoryId, policyId); try { objectLock.lock(); policyLock.lock(); // ////////////////// // General Exception // ////////////////// Content content = contentService.getContent(repositoryId, objectId); exceptionService.objectNotFound(DomainType.OBJECT, content, objectId); exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_ADD_POLICY_OBJECT, content); Policy policy = contentService.getPolicy(repositoryId, policyId); exceptionService.objectNotFound(DomainType.OBJECT, policy, policyId); exceptionService.permissionDenied(callContext, repositoryId, PermissionMapping.CAN_ADD_POLICY_POLICY, policy); // ////////////////// // Specific Exception // ////////////////// TypeDefinition td = typeManager.getTypeDefinition(repositoryId, content); if (!td.isControllablePolicy()) exceptionService.constraint(objectId, "appyPolicy cannot be performed on the object whose controllablePolicy = false"); // ////////////////// // Body of the method // ////////////////// contentService.applyPolicy(callContext, repositoryId, policyId, objectId, extension); nemakiCachePool.get(repositoryId).removeCmisCache(objectId); } finally { objectLock.unlock(); policyLock.unlock(); } }
From source file:net.solarnetwork.node.io.rxtx.RxtxDataCollectorFactory.java
@Override public DataCollector getDataCollectorInstance(SerialPortBeanParameters params) { Lock lock = acquireLock(); try {//w w w . j a v a2 s .c o m CommPortIdentifier portId = getCommPortIdentifier(); // establish the serial port connection SerialPort port = (SerialPort) portId.open(params.getCommPortAppName(), 2000); AbstractSerialPortDataCollector obj; if (params instanceof DataCollectorSerialPortBeanParameters) { DataCollectorSerialPortBeanParameters dcParams = (DataCollectorSerialPortBeanParameters) params; if (dcParams.getMagicEOF() != null) { obj = new SerialPortVariableDataCollector(port, dcParams.getBufferSize(), dcParams.getMagic(), dcParams.getMagicEOF(), dcParams.getMaxWait()); } else { obj = new SerialPortDataCollector(port, dcParams.getBufferSize(), dcParams.getMagic(), dcParams.getReadSize(), dcParams.getMaxWait()); } } else { obj = new SerialPortDataCollector(port); } setupSerialPortSupport(obj, params); if (params instanceof DataCollectorSerialPortBeanParameters) { DataCollectorSerialPortBeanParameters dcParams = (DataCollectorSerialPortBeanParameters) params; obj.setToggleDtr(dcParams.isToggleDtr()); obj.setToggleRts(dcParams.isToggleRts()); } return new PortLockedDataCollector(obj, portId.getName(), lock); } catch (PortInUseException e) { lock.unlock(); throw new RuntimeException(e); } catch (RuntimeException e) { lock.unlock(); throw e; } }
From source file:net.myrrix.online.ServerRecommender.java
private float[] buildAnonymousUserFeatures(long[] 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(); FastByIDMap<float[]> Y = generation.getY(); Solver ytySolver = generation.getYTYSolver(); if (ytySolver == null) { throw new NotReadyException(); }/* ww w . ja v a2 s .c o m*/ float[] anonymousUserFeatures = null; Lock yLock = generation.getYLock().readLock(); boolean anyItemIDFound = false; for (int j = 0; j < itemIDs.length; j++) { long itemID = itemIDs[j]; float[] itemFeatures; yLock.lock(); try { itemFeatures = Y.get(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:com.cloudera.oryx.als.serving.ServerRecommender.java
/** * Computes items most similar to an item or items. The returned items have the highest average similarity * to the given items.// w w w . jav a 2 s . c o m * * @param itemIDs items for which most similar items are required * @param howMany maximum number of similar items to return; fewer may be returned * @param rescorer rescoring function used to modify item-item similarities before ranking results * @return {@link IDValue}s representing the top recommendations for the user, ordered by quality, * descending. The score associated to it is an opaque value. Larger means more similar, but no further * interpretation may necessarily be applied. * @throws NoSuchItemException if any of the items is not known in the model * @throws NotReadyException if the recommender has no model available yet */ @Override public List<IDValue> mostSimilarItems(String[] itemIDs, int howMany, PairRescorer rescorer) throws NoSuchItemException, NotReadyException { Preconditions.checkArgument(howMany > 0, "howMany must be positive"); long[] longItemIDs = new long[itemIDs.length]; for (int i = 0; i < longItemIDs.length; i++) { longItemIDs[i] = StringLongMapping.toLong(itemIDs[i]); } Generation generation = getCurrentGeneration(); LongObjectMap<float[]> Y = generation.getY(); Lock yLock = generation.getYLock().readLock(); yLock.lock(); try { List<float[]> itemFeatures = Lists.newArrayListWithCapacity(itemIDs.length); for (long longItemID : longItemIDs) { float[] features = Y.get(longItemID); if (features != null) { itemFeatures.add(features); } } if (itemFeatures.isEmpty()) { throw new NoSuchItemException(Arrays.toString(itemIDs)); } float[][] itemFeaturesArray = itemFeatures.toArray(new float[itemFeatures.size()][]); return translateToStringIDs(TopN.selectTopN(new MostSimilarItemIterator(Y.entrySet().iterator(), longItemIDs, itemFeaturesArray, rescorer, generation.getIDMapping()), howMany)); } finally { yLock.unlock(); } }
From source file:com.netprogs.minecraft.plugins.social.SocialPerson.java
public void addIgnore(SocialPerson memberPerson) { Lock lock = rwIgnoreLock.writeLock(); lock.lock();// w ww . ja va2 s .c o m try { String playerName = memberPerson.getName(); person.getIgnoreList().add(playerName); SocialNetworkPlugin.log("[" + person.getName() + "] is now ignoring " + playerName); } finally { lock.unlock(); } }
From source file:com.ibm.broker.analytics.r.RNode.java
/** * Parse and evaluate the specified script on the provided Rserve connection. * The script will be checked to see if has been updated before it is parsed and evaluated. * @param connection the established Rserve connection to use. * @param script the script to parse and evaluate. * @throws RNodeException if a problem occurs parsing or evaluating the specified script. * @throws MbException if a problem occurs during user trace processing. *//*w w w .j av a 2 s . c o m*/ private void runScript(Connection connection, RNodeScript script) throws RNodeException, MbException { final String methodName = "runScript"; RNodeLog.logUserTrace(this, methodName, 7826, "About to evaluate file using R runtime", getName(), script.getFileName()); try { // Check to see if the script has been updated. script.update(); // Check to see if we need to update the parsed script. // The file may have been updated since we last parsed it. String parsedScriptVariable = ".iib_r_parsed_script_" + script.getKey(); Lock readLock = script.getReadLock(); readLock.lock(); try { if (connection.checkScriptVersion(script.getKey(), script.getVersion())) { // Assign the script contents to an R variable. String scriptVariable = ".iib_r_script_" + script.getKey(); connection.assign(scriptVariable, script.getContent()); // Parse the script contents on the Rserve server into an R language object. // We use try, as it also allows us to retrieve the error messages from the R runtime. REXP result = connection.parseAndEval( "try(" + parsedScriptVariable + " <- parse(text=" + scriptVariable + "),silent=TRUE)"); if (result.inherits("try-error")) { throw new RNodeException(this, methodName, 7810, "R runtime failed to parse file contents", getName(), script.getFileName(), result.asString()); } } } finally { readLock.unlock(); } // Evaluate the R script on the Rserve server. // We use try, as it also allows us to retrieve the error messages from the R runtime. REXP result = connection.parseAndEval("try(eval(" + parsedScriptVariable + "),silent=TRUE)"); // Check to see if an error occurred - if so, throw an exception containing the error messages. if (result.inherits("try-error")) { throw new RNodeException(this, methodName, 7811, "R runtime failed to evaluate file contents", getName(), script.getFileName(), result.asString()); } RNodeLog.logUserTrace(this, methodName, 7827, "R runtime successfully evaluated file", getName(), script.getFileName()); } catch (REngineException | REXPMismatchException e) { throw new RNodeException(this, methodName, 7811, "R runtime failed to evaluate file contents", getName(), script.getFileName(), e.getMessage()); } }