List of usage examples for java.util.concurrent.locks ReentrantLock unlock
public void unlock()
From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java
/** * Abort database transaction/*w w w. ja v a 2 s .c o m*/ * * Note:Database already in transaction * * @param connection * {@link Connection} to underlying database * @param needsWrite * if true, tables will be locked if needed * @param needsTransaction * TODO * @throws AnzoException * {@link ExceptionConstants.RDB#DIDNT_START_RDB_TRANSACTION} if this thread didn't start the transaction * @throws AnzoException * {@link ExceptionConstants.RDB#FAILED_ROLLBACK_RDB_TRANSACTION} if there was a problem rolling back the connection */ protected void abort(Connection connection, boolean needsWrite, boolean needsTransaction) throws AnzoException { long start = 0; if (stats.isEnabled()) { start = System.currentTimeMillis(); stats.getAbortUse().increment(); } try { ReentrantLock lock = connectionLocks.get(connection); if (lock == null) { lock = new ReentrantLock(); connectionLocks.put(connection, lock); } if (lock.isLocked()) { if (lock.isHeldByCurrentThread()) { try { if (needsTransaction) { ArrayList<AnzoException> exceptions = null; try { if (!connection.isClosed()) { try { connection.rollback(); connection.setAutoCommit(true); } catch (SQLException e) { log.error(LogUtils.RDB_MARKER, "Error rolling back transaction", e); exceptions = new ArrayList<AnzoException>(); exceptions.add(new AnzoException( ExceptionConstants.RDB.FAILED_ROLLBACK_RDB_TRANSACTION, e)); } try { unlockTable(connection, needsWrite); } catch (AnzoException ae) { log.error(LogUtils.RDB_MARKER, "Error unlocking table", ae); if (exceptions == null) { exceptions = new ArrayList<AnzoException>(); } exceptions.add(ae); } } } catch (SQLException e) { log.error(LogUtils.RDB_MARKER, "Error rollingback jdbc transaction", e); exceptions = new ArrayList<AnzoException>(); exceptions.add(new AnzoException( ExceptionConstants.RDB.FAILED_ROLLBACK_RDB_TRANSACTION, e)); } if (exceptions != null && exceptions.size() > 0) { throw new CompoundAnzoException(exceptions, ExceptionConstants.RDB.FAILED_ROLLBACK_RDB_TRANSACTION); } } } finally { lock.unlock(); nodeLayout.clearUncommittedCache(); } } else { throw new AnzoException(ExceptionConstants.RDB.DIDNT_START_RDB_TRANSACTION); } } } finally { if (stats.isEnabled()) { stats.getAbortDuration().addTime((System.currentTimeMillis() - start)); } } }
From source file:org.openspaces.persistency.cassandra.HectorCassandraClient.java
/** * Creates a column family on the configured keyspace if one does not already exist. * * @param metadata The metadata describing the column family to create. * @param shouldPersist Should the {@link ColumnFamilyMetadata} instance be persisted to the * internal metadata column family. */// w w w . j a va2s. c o m public void createColumnFamilyIfNecessary(ColumnFamilyMetadata metadata, boolean shouldPersist) { ReentrantLock lockForType = namedLock.forName(metadata.getTypeName()); lockForType.lock(); try { final boolean columnFamilyExists = isColumnFamilyExists(metadata); if (columnFamilyExists) { if (metadata != ColumnFamilyMetadataMetadata.INSTANCE) { metadataCache.addColumnFamilyMetadata(metadata.getTypeName(), metadata); // we persist the metadata again here, because it is possible // that the table creation was successful but writing the internal metadata // failed. without this, we will never write the internal metadata. // the assumption here is that we write the exact same metadata. if (shouldPersist) { persistColumnFamilyMetadata(metadata); } } return; } ThriftCfDef cfDef = (ThriftCfDef) HFactory.createColumnFamilyDefinition(keyspace.getKeyspaceName(), metadata.getColumnFamilyName()); cfDef.setColumnMetadata(new ArrayList<ColumnDefinition>()); cfDef.setDefaultValidationClass(ValidatorClassInferer.getBytesTypeValidationClass()); cfDef.setComparatorType(StringSerializer.get().getComparatorType()); cfDef.setKeyAlias(StringSerializer.get().toByteBuffer(metadata.getKeyName())); cfDef.setKeyValidationClass(ValidatorClassInferer.infer(metadata.getKeyType())); cfDef.setComment(metadata.getTypeName()); if (columnFamilyGcGraceSeconds != null) { cfDef.setGcGraceSeconds(columnFamilyGcGraceSeconds); } for (TypedColumnMetadata columnMetadata : metadata.getColumns().values()) { String validationClass = ValidatorClassInferer.infer(columnMetadata.getType()); addColumnDefinitionToColumnFamilyDefinition(metadata, cfDef, columnMetadata.getFullName(), validationClass); } // create stub columns for statically defined indexes of dynamic properties for (String index : metadata.getIndexes()) { // we took care of these in the previous for loop if (metadata.getColumns().containsKey(index)) { continue; } String validationClass = ValidatorClassInferer.getBytesTypeValidationClass(); addColumnDefinitionToColumnFamilyDefinition(metadata, cfDef, index, validationClass); } if (logger.isInfoEnabled()) { logger.info("Creating column family: " + metadata); } try { // first create the actual column family try { cluster.addColumnFamily(cfDef, true); } catch (Exception e) { // This could be due to current type introduction // If column family already exists, we can ignore this exception, otherwise we propage if (logger.isInfoEnabled()) { logger.info("Column family creation failed, " + "waiting " + (SLEEP_BEFORE_RETRY / 1000) + " seconds and then testing to see whether " + "the column family was already created.", e); } Thread.sleep(SLEEP_BEFORE_RETRY); if (!isColumnFamilyExists(metadata)) { throw e; } } if (metadata != ColumnFamilyMetadataMetadata.INSTANCE) { metadataCache.addColumnFamilyMetadata(metadata.getTypeName(), metadata); if (shouldPersist) { persistColumnFamilyMetadata(metadata); } } } catch (Exception e) { throw new SpaceCassandraSchemaUpdateException("Failed adding column family definition to cassandra", e, true); } } finally { lockForType.unlock(); } }
From source file:edu.usu.sdl.openstorefront.service.ComponentServiceImpl.java
@Override public void processComponentUpdates() { ReentrantLock lock = new ReentrantLock(); lock.lock();/* www .j ava 2 s . c o m*/ try { ComponentUpdateQueue updateQueueExample = new ComponentUpdateQueue(); updateQueueExample.setNodeId(PropertiesManager.getNodeName()); List<ComponentUpdateQueue> componentUpdateQueues = persistenceService .queryByExample(ComponentUpdateQueue.class, updateQueueExample); if (componentUpdateQueues.isEmpty() == false) { //Get the latest entries Map<String, ComponentUpdateQueue> componentMap = new HashMap<>(); for (ComponentUpdateQueue updateQueue : componentUpdateQueues) { if (componentMap.containsKey(updateQueue.getUpdateId())) { ComponentUpdateQueue existing = componentMap.get(updateQueue.getUpdateId()); if (existing.getUpdateDts().before(updateQueue.getUpdateDts())) { componentMap.put(updateQueue.getUpdateId(), updateQueue); } } else { componentMap.put(updateQueue.getUpdateId(), updateQueue); } } List<Component> componentsToIndex = new ArrayList<>(); for (ComponentUpdateQueue componentUpdate : componentMap.values()) { String componentId = componentUpdate.getComponentId(); Component component = persistenceService.findById(Component.class, componentId); if (component != null) { component.setLastActivityDts(componentUpdate.getUpdateDts()); persistenceService.persist(component); getUserService().checkComponentWatches(component); componentsToIndex.add(component); } else { log.log(Level.FINE, "Component not found to update last Activity. Component may have been removed.", "Check component Id: " + componentId); } } getSearchService().indexComponents(componentsToIndex); //remove processed records for (ComponentUpdateQueue updateQueue : componentUpdateQueues) { ComponentUpdateQueue componentUpdateQueue = persistenceService .findById(ComponentUpdateQueue.class, updateQueue.getUpdateId()); if (componentUpdateQueue != null) { persistenceService.delete(componentUpdateQueue); } } } } finally { lock.unlock(); } }
From source file:la2launcher.MainFrame.java
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed final long initTime = new Date().getTime(); ReentrantLock lock = new ReentrantLock(); final String patcherUrl = "http://" + updateHost + "/hf//updater.lst.la2";//new ArrayBlockingQueue<Runnable>(10000) final ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS, new ArrayBlockingQueue<Runnable>(10000)); filesProcessed = 0;/*from w w w . jav a 2 s . c o m*/ tpe.execute(new Runnable() { @Override public void run() { jTextArea2.setText(""); DefaultTableModel model = (DefaultTableModel) jTable2.getModel(); jProgressBar1.setMinimum(0); jProgressBar1.setMaximum(model.getRowCount()); jProgressBar1.setValue(0); jLabel4.setText("0/" + model.getRowCount()); for (int i = 0; i < model.getRowCount(); i++) { boolean checked = (Boolean) model.getValueAt(i, 1); String fileName = (String) model.getValueAt(i, 0); if (checked) { tpe.execute(new Runnable() { @Override public void run() { final String fileUrl = "http://" + updateHost + "/hf/" + fileName.replace("\\", "/") + ".la2"; try { printMsg(" " + fileUrl); File file = new File(gamePath + fileName + ".rar"); File fileExt = new File(gamePath + fileName); file.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(file); CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet(fileUrl); CloseableHttpResponse response1 = httpclient.execute(httpGet); HttpEntity entity1 = response1.getEntity(); copyStream(entity1.getContent(), fos, new CopyListener() { @Override public void transfered(int n) { bytesRecieved += n; bytesRecievedTotal += n; } }); response1.close(); fos.close(); printMsg("?? : " + fileName); lock.lock(); //fixBzip2File(file); //printMsg(" ?"); extractArchive(file.getAbsolutePath()); //BZip2CompressorInputStream bz = new BZip2CompressorInputStream(new FileInputStream(file)); //OutputStream pout = new FileOutputStream(fileExt); //copyStream(archStream, pout, null); //pout.close(); //archStream.close(); //jTextArea2.setText(jTextArea2.getText() + "\r\n? : " + fileName); printMsg("? : " + fileName); //file.delete(); // File tgt = new File(gamePath + fileName); // if (tgt.exists()) { // tgt.delete(); // } //tgt.getParentFile().mkdirs(); //Files.move(fileExt.toPath(), new File(gamePath + fileName).toPath()); //jTextArea2.setText(jTextArea2.getText() + "\r\n ??: " + fileName); printMsg(" ??: " + fileName); jProgressBar1.setIndeterminate(false); jLabel4.setText((++filesProcessed) + "/" + model.getRowCount()); jProgressBar1.setValue((int) filesProcessed); lock.unlock(); } catch (IOException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (Exception ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } } }); } } } }); jButton5.setEnabled(false); jButton6.setEnabled(false); jButton7.setEnabled(false); jButton8.setEnabled(false); jButton9.setEnabled(false); jButton10.setEnabled(false); jProgressBar1.setIndeterminate(true); new Thread() { @Override public void run() { do { long millis = new Date().getTime(); try { sleep(300); } catch (InterruptedException ex) { Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex); } millis = new Date().getTime() - millis; BigDecimal totBig = new BigDecimal(bytesRecievedTotal / (1024 * 1024.0)); totBig = totBig.setScale(2, BigDecimal.ROUND_CEILING); jLabel5.setText("?: " + (bytesRecieved / millis) + "KB/s. : " + totBig + " MB"); bytesRecieved = 0; } while (tpe.getActiveCount() > 0); tpe.shutdown(); jButton5.setEnabled(true); jButton6.setEnabled(true); jButton7.setEnabled(true); jButton8.setEnabled(true); jButton9.setEnabled(true); jButton10.setEnabled(true); jProgressBar1.setIndeterminate(false); printMsg(" " + (new Date().getTime() - initTime) + " ?."); } }.start(); }
From source file:com.alibaba.wasp.master.AssignmentManager.java
/** * Unassigns the specified entityGroup.//from ww w .ja v a 2 s .c o m * <p> * Updates the EntityGroupState and sends the CLOSE RPC unless entityGroup is * being split by entityGroupserver; then the unassign fails (silently) * because we presume the entityGroup being unassigned no longer exists (its * been split out of existence). TODO: What to do if split fails and is rolled * back and parent is revivified? * <p> * If a EntityGroupPlan is already set, it will remain. * * @param entityGroup * server to be unassigned * @param force * if entityGroup should be closed even if already closing */ public void unassign(EntityGroupInfo entityGroup, boolean force, ServerName dest) { // TODO: Method needs refactoring. Ugly buried returns throughout. Beware! LOG.debug("Starting unassignment of entityGroup " + entityGroup.getEntityGroupNameAsString() + " (offlining)"); String encodedName = entityGroup.getEncodedName(); // Grab the state of this entityGroup and synchronize on it int versionOfClosingNode = -1; // We need a lock here as we're going to do a put later and we don't want // multiple states // creation ReentrantLock lock = locker.acquireLock(encodedName); EntityGroupState state = entityGroupStates.getEntityGroupTransitionState(encodedName); try { if (state == null) { // Create the znode in CLOSING state try { state = entityGroupStates.getEntityGroupState(entityGroup); if (state == null || state.getServerName() == null) { // We don't know where the entityGroup is, offline it. // No need to send CLOSE RPC entityGroupOffline(entityGroup); return; } versionOfClosingNode = ZKAssign.createNodeClosing(watcher, entityGroup, state.getServerName()); if (versionOfClosingNode == -1) { LOG.debug("Attempting to unassign entityGroup " + entityGroup.getEntityGroupNameAsString() + " but ZK closing node " + "can't be created."); return; } } catch (KeeperException ee) { Exception e = ee; if (e instanceof NodeExistsException) { // Handle race between master initiated close and entityGroupserver // orchestrated splitting. See if existing node is in a // SPLITTING or SPLIT state. If so, the entityGroupserver started // an op on node before we could get our CLOSING in. Deal. NodeExistsException nee = (NodeExistsException) e; String path = nee.getPath(); try { if (isSplitOrSplitting(path)) { LOG.debug(path + " is SPLIT or SPLITTING; " + "skipping unassign because entityGroup no longer exists -- its split"); return; } } catch (KeeperException.NoNodeException ke) { LOG.warn("Failed getData on SPLITTING/SPLIT at " + path + "; presuming split and that the entityGroup to unassign, " + encodedName + ", no longer exists -- confirm", ke); return; } catch (KeeperException ke) { LOG.error("Unexpected zk state", ke); } catch (DeserializationException de) { LOG.error("Failed parse", de); } } // If we get here, don't understand whats going on -- abort. server.abort("Unexpected ZK exception creating node CLOSING", e); return; } state = entityGroupStates.updateEntityGroupState(entityGroup, EntityGroupState.State.PENDING_CLOSE); } else if (force && (state.isPendingClose() || state.isClosing())) { LOG.debug("Attempting to unassign entityGroup " + entityGroup.getEntityGroupNameAsString() + " which is already " + state.getState() + " but forcing to send a CLOSE RPC again "); state.updateTimestampToNow(); } else { LOG.debug("Attempting to unassign entityGroup " + entityGroup.getEntityGroupNameAsString() + " but it is " + "already in transition (" + state.getState() + ", force=" + force + ")"); return; } unassign(entityGroup, state, versionOfClosingNode, dest, true); } finally { lock.unlock(); } }
From source file:org.apache.hadoop.hbase.master.AssignmentManager.java
/** * Unassigns the specified region./*from w w w . j a va 2 s. c o m*/ * <p> * Updates the RegionState and sends the CLOSE RPC unless region is being * split by regionserver; then the unassign fails (silently) because we * presume the region being unassigned no longer exists (its been split out * of existence). TODO: What to do if split fails and is rolled back and * parent is revivified? * <p> * If a RegionPlan is already set, it will remain. * * @param region server to be unassigned * @param force if region should be closed even if already closing */ public void unassign(HRegionInfo region, boolean force, ServerName dest) { // TODO: Method needs refactoring. Ugly buried returns throughout. Beware! LOG.debug("Starting unassign of " + region.getRegionNameAsString() + " (offlining), current state: " + regionStates.getRegionState(region)); String encodedName = region.getEncodedName(); // Grab the state of this region and synchronize on it int versionOfClosingNode = -1; // We need a lock here as we're going to do a put later and we don't want multiple states // creation ReentrantLock lock = locker.acquireLock(encodedName); RegionState state = regionStates.getRegionTransitionState(encodedName); boolean reassign = true; try { if (state == null) { // Region is not in transition. // We can unassign it only if it's not SPLIT/MERGED. state = regionStates.getRegionState(encodedName); if (state != null && state.isUnassignable()) { LOG.info("Attempting to unassign " + state + ", ignored"); // Offline region will be reassigned below return; } // Create the znode in CLOSING state try { if (state == null || state.getServerName() == null) { // We don't know where the region is, offline it. // No need to send CLOSE RPC LOG.warn("Attempting to unassign a region not in RegionStates" + region.getRegionNameAsString() + ", offlined"); regionOffline(region); return; } versionOfClosingNode = ZKAssign.createNodeClosing(watcher, region, state.getServerName()); if (versionOfClosingNode == -1) { LOG.info("Attempting to unassign " + region.getRegionNameAsString() + " but ZK closing node " + "can't be created."); reassign = false; // not unassigned at all return; } } catch (KeeperException e) { if (e instanceof NodeExistsException) { // Handle race between master initiated close and regionserver // orchestrated splitting. See if existing node is in a // SPLITTING or SPLIT state. If so, the regionserver started // an op on node before we could get our CLOSING in. Deal. NodeExistsException nee = (NodeExistsException) e; String path = nee.getPath(); try { if (isSplitOrSplittingOrMergedOrMerging(path)) { LOG.debug(path + " is SPLIT or SPLITTING or MERGED or MERGING; " + "skipping unassign because region no longer exists -- its split or merge"); reassign = false; // no need to reassign for split/merged region return; } } catch (KeeperException.NoNodeException ke) { LOG.warn("Failed getData on SPLITTING/SPLIT at " + path + "; presuming split and that the region to unassign, " + encodedName + ", no longer exists -- confirm", ke); return; } catch (KeeperException ke) { LOG.error("Unexpected zk state", ke); } catch (DeserializationException de) { LOG.error("Failed parse", de); } } // If we get here, don't understand whats going on -- abort. server.abort("Unexpected ZK exception creating node CLOSING", e); reassign = false; // heading out already return; } state = regionStates.updateRegionState(region, State.PENDING_CLOSE); } else if (state.isFailedOpen()) { // The region is not open yet regionOffline(region); return; } else if (force && state.isPendingCloseOrClosing()) { LOG.debug("Attempting to unassign " + region.getRegionNameAsString() + " which is already " + state.getState() + " but forcing to send a CLOSE RPC again "); if (state.isFailedClose()) { state = regionStates.updateRegionState(region, State.PENDING_CLOSE); } state.updateTimestampToNow(); } else { LOG.debug("Attempting to unassign " + region.getRegionNameAsString() + " but it is " + "already in transition (" + state.getState() + ", force=" + force + ")"); return; } unassign(region, state, versionOfClosingNode, dest, true, null); } finally { lock.unlock(); // Region is expected to be reassigned afterwards if (reassign && regionStates.isRegionOffline(region)) { assign(region, true); } } }