concurrency issues.
767463
int reallocate(int index, int offset, int oldLen, int newLen) {

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) JmfTr.entry(this, tc, "reallocate", new Object[]{Integer.valueOf(index), Integer.valueOf(offset), Integer.valueOf(oldLen), Integer.valueOf(newLen)});

    // Get oTable index for the next field after this one, if any. We can be
    // guaranteed that its offsetIndex is one greater than ours, since this is a
    // varying length field.
    int oInx = map.fields[index].offsetIndex + 1;

    // Update the oTable in place
    while (oInx < oTable.length) {
      oTable[oInx++] += (newLen - oldLen);
    }

    // Compute the length of the balance, after the varying length field
    int balance = (messageOffset + length) - offset - 4 - oldLen;

    // Create new contents entry, and update related offsets and lengths
    byte[] oldcontents = contents;
    int oldMessageOffset = messageOffset;
    int oldDataOffset = dataOffset;
    int oldTableOffset = tableOffset;
    length += (newLen - oldLen);
    contents = new byte[length];
    messageOffset = 0;
    tableOffset = dataOffset = oldTableOffset - oldMessageOffset;

    // Copy the schemata ids
    System.arraycopy(oldcontents, oldMessageOffset, contents, 0, tableOffset);

    // Write the offset table into the new array
    for (int i = 0; i < oTable.length; i++) {
      ArrayUtil.writeInt(contents, dataOffset, oTable[i]);
      dataOffset += 4;
    }

    // Copy up to the point where the length is changing
    System.arraycopy(oldcontents, oldDataOffset, contents, dataOffset, offset - oldDataOffset);

    // Copy balance of data after varying length field
    if (balance > 0) {
      System.arraycopy(oldcontents, offset + 4 + oldLen, contents, length - balance, balance);
    }

    reallocated = true;

    // We have a new contents buffer, so it can't be shared
    sharedContents = false;

    // Ensure any dependent JSMessageData parts in the cache are updated.
    reallocated(contents, -1);

    int result = offset - oldMessageOffset;

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) JmfTr.exit(this, tc, "reallocate", Integer.valueOf(result));
    return result;
  }
266147
private void repin() {
		if (logger.isLoggable(Level.WARNING))
			logger.warning("Tx." + txNum + " is re-pinning all buffers");
		
		try {
			// Copy the set of pinned buffers to avoid ConcurrentModificationException
			List<BlockId> blksToBeRepinned = new LinkedList<BlockId>();
			Map<BlockId, Integer> pinCounts = new HashMap<BlockId, Integer>();
			List<Buffer> buffersToBeUnpinned = new LinkedList<Buffer>();
			
			// Record the buffers to be un-pinned and the blocks to be re-pinned
			for (Entry<BlockId, PinnedBuffer> entry : pinnedBuffers.entrySet()) {
				blksToBeRepinned.add(entry.getKey());
				pinCounts.put(entry.getKey(), entry.getValue().pinnedCount);
				buffersToBeUnpinned.add(entry.getValue().buffer);
			}
			
			// Un-pin all buffers it has
			for (Buffer buf : buffersToBeUnpinned)
				unpin(buf);

			// Wait other threads pinning blocks
			synchronized (bufferPool) {
				bufferPool.wait(MAX_TIME);
			}

			// Re-pin all blocks
			for (BlockId blk : blksToBeRepinned)
				pin(blk);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
740548
public void uniq() {
        if (size <= 1) { return; }
        int cursor = 0;
        for (int i=1; i<size; i++) {
            if (elements[cursor] != elements[i]) {
                cursor++;
                elements[cursor] = elements[i];
            }
        }
        size = cursor+1;
    }
97544
protected void inconsistent(Iterable<? extends K> keys, StoreAccessException because, StoreAccessException... cleanup) {
    pacedErrorLog("Ehcache keys {} in possible inconsistent state", keys, because);
  }
517001
function update() {
		while (waiting.length && count < concurrency) (function() {
			var t = waiting.shift()
			
			if (inProg[t.task.id]) {
				inProg[t.task.id].push(t.cb)
				return
			} else {
				inProg[t.task.id] = [t.cb]
				count++
				processor(t.task, function() {
					var args = arguments

					if (!inProg[t.task.id]) return // probably callback called twice
	
					count--
					inProg[t.task.id].forEach(function(cb) { cb.apply(null, args) })
					delete inProg[t.task.id]
	
					setImmediate(update)
				})
			}	
		})()
	}
1173998
private void doInterruptAllWaitingThreads() {
    	//Interrupt all the threads
    	for (int i=0; i<nThreads; i++) {
    		threads[i].interrupt();
    	}
    	
    	synchronized(lock) {
    		lock.notify();
    	}
    }
870152
void writeLock(int count) {
      if (count > 0 && counter != null)
         counter.acquireShared(count);
      sync.acquireShared(1);
   }
848646
private static void add(IntegerVector semantics, TernaryVector index) {
        // Lock on the semantic vector to avoid a race condition with another
        // thread updating its semantics.  Use the vector to avoid a class-level
        // lock, which would limit the concurrency.
        synchronized(semantics) {
            for (int p : index.positiveDimensions())
                semantics.add(p, 1);
            for (int n : index.negativeDimensions())
                semantics.add(n, -1);
        }
    }
606945
public synchronized void flushInsert()
    {
        if (!insertForUpdateList.isEmpty())
        {
            int sent = this.submitInsert(insertForUpdateList);
            if (sent < insertForUpdateList.size())
            {
                this.submitInsertTaskToQueue(this.createInsertTaskForObjects(insertForUpdateList.subList(sent, insertForUpdateList.size())), processedInserts);
            }
            this.insertForUpdateList = new MithraFastList(insertBatchSize);
        }

        if (!insertList.isEmpty())
        {
            int sent = this.submitInsert(insertList);
            if (sent < insertList.size())
            {
                this.submitInsertTaskToQueue(this.createInsertTaskForObjects(insertList.subList(sent, insertList.size())), processedInserts);
            }
            this.insertList = new MithraFastList(insertBatchSize);
        }
    }
551376
private static void mult(int[] s1, int s1Len, int[] s2, int s2Len, int[] dst) {
        for (int i = 0; i < s1Len; i++) {
            long v = s1[i] & LONG_MASK;
            long p = 0L;
            for (int j = 0; j < s2Len; j++) {
                p += (dst[i + j] & LONG_MASK) + v * (s2[j] & LONG_MASK);
                dst[i + j] = (int) p;
                p >>>= 32;
            }
            dst[i + s2Len] = (int) p;
        }
    }
264285
private BThreadSyncSnapshot handleContinuationPending(ContinuationPending cbs, Context jsContext) throws IllegalStateException {
        final Object capturedStatement = cbs.getApplicationState();
        
        if ( capturedStatement instanceof SyncStatement ) {
            final SyncStatement syncStatement = (SyncStatement) cbs.getApplicationState();
            return bss.copyWith(cbs.getContinuation(), syncStatement);
            
        } else if ( capturedStatement instanceof ForkStatement ) {
            ForkStatement forkStmt = (ForkStatement) capturedStatement;
            forkStmt.setForkingBThread(bss);
            
            final ScriptableObject globalScope = jsContext.initStandardObjects();
            try ( ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BThreadSyncSnapshotOutputStream btos = new BThreadSyncSnapshotOutputStream(baos, globalScope) ) {
                btos.writeObject(cbs.getContinuation());
                btos.flush();
                baos.flush();
                forkStmt.setSerializedContinuation(baos.toByteArray());
                
            } catch (IOException ex) {
                Logger.getLogger(BPEngineTask.class.getName()).log(Level.SEVERE, "Error while serializing continuation during fork:" + ex.getMessage(), ex);
                throw new RuntimeException("Error while serializing continuation during fork:" + ex.getMessage(), ex);
            }
            
            listener.addFork(forkStmt);
            return continueParentOfFork(cbs, jsContext);
            
        } else {
            throw new IllegalStateException("Captured a statement of an unknown type: " + capturedStatement);
        }
    }
595651
public void consistencyCheck() {
        for (int iRow = 0; iRow < 9; iRow++) {
            for (int iCol = 0; iCol < 9; iCol++) {
                Cell cell = cells[iRow][iCol];
                Integer value = cell.getValue();
                if (value != null) {
                    if (! cell.getFree().isEmpty()) {
                        throw new IllegalStateException("free not empty");
                    }
                    // any containing group
                    for (Cell other: cell.getExCells()) {
                        // must not occur in any of the other cells
                        if (value.equals(other.getValue())) {
                            throw new IllegalStateException("duplicate");
                        }
                        // must not occur in the permissibles of any of the other cells
                        if (other.getFree().contains(value)) {
                            throw new IllegalStateException("not eliminated");
                        }
                    }
                }
            }
        }
        
        for (int i = 0; i < rows.length; i++) {
            Set<Integer> aSet = new HashSet<Integer>();
            for (int j = 0; j < rows[i].getCells().size(); j++) {
                Cell cell = rows[i].getCells().get(j);
                Integer value = cell.getValue();
                if (value != null) {
                    aSet.add(value);
                } else {
                    aSet.addAll(cell.getFree());
                }
            }
            if (! aSet.equals(CellGroup.ALL_NINE)) {
                throw new IllegalStateException("deficit in row");
            }
        }
        
        for (int i = 0; i < cols.length; i++) {
            Set<Integer> aSet = new HashSet<Integer>();
            for (int j = 0; j < cols[i].getCells().size(); j++) {
                Cell cell = cols[i].getCells().get(j);
                Integer value = cell.getValue();
                if (value != null) {
                    aSet.add(value);
                } else {
                    aSet.addAll(cell.getFree());
                }
            }
            if (! aSet.equals(CellGroup.ALL_NINE)) {
                throw new IllegalStateException("deficit in column");
            }
        }

        for (int ir = 0; ir < sqrs.length; ir++) {
            for (int ic = 0; ic < sqrs[ir] .length; ic++) {
                Set<Integer> aSet = new HashSet<Integer>();
                for (int j = 0; j < sqrs[ir][ic].getCells().size(); j++) {
                    Cell cell = sqrs[ir][ic].getCells().get(j);
                    Integer value = cell.getValue();
                    if (value != null) {
                        aSet.add(value);
                    } else {
                        aSet.addAll(cell.getFree());
                    }
                }
                if (! aSet.equals(CellGroup.ALL_NINE)) {
                    throw new IllegalStateException("deficit in square");
                }
            }
        }
        System.out.println("+++ check OK +++");
    }
832603
@Override
    public void onKnownIssueNotSynchronized(final AcraReport pReport, final Issue pIssue)
            throws SynchronizationException {

        IssueDescriptionReader reader = null;
        try {
            reader = new IssueDescriptionReader(pIssue);

        } catch (final IssueParseException e) {
            throw new SynchronizationException("Unable to parse description of issue "
                    + pIssue.getId(), e);
        }

        final IssueDescriptionBuilder builder = new IssueDescriptionBuilder(reader.getStacktrace());
        builder.setOccurrences(reader.getOccurrences());
        builder.addOccurrence(IssueDescriptionUtils.toErrorOccurrence(pReport));

        pIssue.setDescription(builder.build());

        try {
            redmineClient.updateIssue(pIssue);
        } catch (final Exception e) {
            pReport.setStatus(SyncStatus.FAILURE);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Failure while updating issue: \n{}",
                        ToStringBuilder.reflectionToString(pIssue, ToStringStyle.MULTI_LINE_STYLE));
            }
            throw new SynchronizationException(
                    String.format("Unable to update issue %s for ACRA report %s", pIssue.getId(),
                            pReport.getId()), e);
        }
        pReport.setStatus(SyncStatus.SUCCESS);
    }
908331
def get_concurrency(self):
        """"""
        method = 'GET'
        endpoint = '/rest/v1.1/users/{}/concurrency'.format(
            self.client.sauce_username)
        return self.client.request(method, endpoint)
1082502
@VisibleForTesting
  void prepareConcurrentMultiGetTasks() {
    multi_get_wait_cnt = 0;
    prepare_multi_get_start_time = DateTime.currentTimeMillis();


    final List<Long> row_base_time_list;
    if (RollupQuery.isValidQuery(rollup_query)) {
      row_base_time_list = prepareRowBaseTimesRollup();
    } else {
      row_base_time_list = prepareRowBaseTimes();
    }

    int next_concurrency_index = 0;
    List<GetRequest> gets_to_prepare = new ArrayList<GetRequest>(batch_size);
    Set<byte[]> tsuids = new ByteSet();
    
    final ByteMap<ByteMap<List<GetRequest>>> all_tsuids_gets;
    if (multiget_no_meta) {
      // prepare the tagvs combinations and base time list
      
      final List<byte[][]> tagv_compinations = prepareAllTagvCompounds();
      all_tsuids_gets = prepareRequestsNoMeta(tagv_compinations, row_base_time_list);
    } else {
      all_tsuids_gets = prepareRequests(row_base_time_list, tags);

    }
    // Iterate over all salts
    for (final Entry<byte[], ByteMap<List<GetRequest>>> salts_entry : all_tsuids_gets.entrySet()) {
      if (gets_to_prepare.size() > 0) { // if we have any gets_to_prepare for previous salt, create a 
                                        // request out of it.
        final MultiGetTask task = new MultiGetTask(tsuids, gets_to_prepare);
        final List<MultiGetTask> mulget_task_list = 
            multi_get_tasks.get((next_concurrency_index++) % concurrency_multi_get);
        mulget_task_list.add(task);
        ++multi_get_wait_cnt;
        multi_get_num_get_requests = multi_get_num_get_requests + gets_to_prepare.size();
        gets_to_prepare = new ArrayList<GetRequest>(batch_size);
        tsuids = new ByteSet();
      }
      byte[] curr_salt = salts_entry.getKey();
      // Iterate over all tsuid's in curr_salt and add them to gets_to_prepare
      for (final Entry<byte[], List<GetRequest>> gets_entry : salts_entry.getValue()) {
        byte[] tsuid = gets_entry.getKey();
      
          for (GetRequest request : gets_entry.getValue()) { 
            if (gets_to_prepare.size() >= batch_size) { // close batch and create a MultiGetTask
              final MultiGetTask task = new MultiGetTask(tsuids, gets_to_prepare);
              final List<MultiGetTask> mulget_task_list = 
                  multi_get_tasks.get((next_concurrency_index++) % concurrency_multi_get);
              mulget_task_list.add(task);
              ++multi_get_wait_cnt;
              multi_get_num_get_requests = multi_get_num_get_requests + gets_to_prepare.size();
              if (LOG.isDebugEnabled()) {
                LOG.debug("Finished preparing MultiGetRequest with " + gets_to_prepare.size() + " requests for salt " + curr_salt + 
                 " for tsuid " + Bytes.pretty(tsuid));
              }
              // prepare a new task list and tsuids
              gets_to_prepare = new ArrayList<GetRequest>(batch_size);
              tsuids = new ByteSet();
            }             
            gets_to_prepare.add(request);
            tsuids.add(gets_entry.getKey());
          }
          tsuids.add(gets_entry.getKey());
      }
    }
   
  
    if (gets_to_prepare.size() > 0) {
      
      final MultiGetTask task = new MultiGetTask(tsuids, gets_to_prepare);
      final List<MultiGetTask> mulget_task_list = 
          multi_get_tasks.get((next_concurrency_index++) % concurrency_multi_get);
      mulget_task_list.add(task);
      ++multi_get_wait_cnt;
      multi_get_num_get_requests = multi_get_num_get_requests + gets_to_prepare.size();
      LOG.debug("Finished preparing MultiGetRequest with " + gets_to_prepare.size());
      gets_to_prepare = new ArrayList<GetRequest>(batch_size);
      tsuids = new ByteSet();
    }

    prepare_multi_get_end_time = DateTime.currentTimeMillis();
    if (LOG.isDebugEnabled()) {
      LOG.debug("Finished preparing concurrency multi get task with " 
          + multi_get_wait_cnt + " tasks using "
          + (prepare_multi_get_end_time - prepare_multi_get_start_time) + "ms");
    }

  }
431153
private void commitMutations(DBTransaction dbTran, long timestamp) {
        Map<ByteBuffer, Map<String, List<Mutation>>> colMutMap = CassandraTransaction.getUpdateMap(dbTran, timestamp);
        if (colMutMap.size() == 0) {
            return;
        }
        m_logger.debug("Committing {} mutations", CassandraTransaction.totalColumnMutations(dbTran));
        
        // The batch_mutate will be retried up to MAX_COMMIT_RETRIES times.
        boolean bSuccess = false;
        for (int attempts = 1; !bSuccess; attempts++) {
            try {
                // Attempt to commit all updates in the the current mutation map.
                Date startDate = new Date();
                m_client.batch_mutate(colMutMap, ConsistencyLevel.ONE);
                timing("commitMutations", startDate);
                if (attempts > 1) {
                    // Since we had a failure and warned about it, confirm which attempt succeeded.
                    m_logger.info("batch_mutate() succeeded on attempt #{}", attempts);
                }
                bSuccess = true;
            } catch (InvalidRequestException ex) {
                // No point in retrying this one.
                m_bFailed = true;
                m_logger.error("batch_mutate() failed", ex);
                throw new RuntimeException("batch_mutate() failed", ex);
            } catch (Exception ex) {
                // If we've reached the retry limit, we fail this commit.
                if (attempts >= m_max_commit_attempts) {
                    m_bFailed = true;
                    m_logger.error("All retries exceeded; abandoning batch_mutate()", ex);
                    throw new RuntimeException("All retries exceeded; abandoning batch_mutate()", ex);
                }
                
                // Report retry as a warning.
                m_logger.warn("batch_mutate() attempt #{} failed: {}", attempts, ex);
                try {
                    // We wait more with each failure.
                    Thread.sleep(attempts * m_retry_wait_millis);
                } catch (InterruptedException e1) {
                    // ignore
                }
                
                // Experience suggests that even for timeout exceptions, the connection
                // may be bad, so we attempt to reconnect. If this fails, it will throw
                // an DBNotAvailableException, which we pass to the caller.
                reconnect(ex);
            }
        }
    }
916730
function (threadId) {
        Multiplexer.connections[threadId] && Multiplexer.connections[threadId].release();
        delete Multiplexer.connections[threadId];
    }