Try to update an old block to a new block.
If there are ongoing create threads running for the old block,
the threads will be returned without updating the block.

@return ongoing create threads if there is any. Otherwise, return null.
975854
private List<Thread> tryUpdateBlock(int namespaceId, 
      Block oldblock, Block newblock) throws IOException {
    lock.writeLock().lock();
    try {
      //check ongoing create threads
      ArrayList<Thread> activeThreads = getActiveThreads(namespaceId, oldblock);
      if (activeThreads != null) {
        return activeThreads;
      }

      DatanodeBlockInfo binfo = volumeMap.get(namespaceId, oldblock);
      if (binfo == null) {
        throw new IOException("Block " + oldblock
            + " doesn't exist or has been recovered to a new generation ");
      }

      File blockFile = binfo.getBlockDataFile().getFile();
  
      long oldgs;
      File oldMetaFile = null;
      if (binfo.isInlineChecksum()) {
        oldgs = BlockInlineChecksumReader
            .getGenerationStampFromInlineChecksumFile(blockFile.getName());
      } else {
        oldMetaFile = BlockWithChecksumFileWriter.findMetaFile(blockFile);
        oldgs = BlockWithChecksumFileReader.parseGenerationStampInMetaFile(
            blockFile, oldMetaFile);
      }
      
    // First validate the update

      //update generation stamp
      if (oldgs > newblock.getGenerationStamp()) {
        throw new IOException("Cannot update block (id=" + newblock.getBlockId()
            + ") generation stamp from " + oldgs
            + " to " + newblock.getGenerationStamp());
      }
      
      //update length
      if (newblock.getNumBytes() > oldblock.getNumBytes()) {
        throw new IOException("Cannot update block file (=" + blockFile
            + ") length from " + oldblock.getNumBytes() + " to " + newblock.getNumBytes());
      }

      // Although we've waited for the active threads all dead before updating
      // the map so there should be no data race there, we still create new
      // ActiveFile object to make sure in case another thread holds it,
      // it won't cause any problem for us.
      //
      try {
        volumeMap.copyOngoingCreates(namespaceId, oldblock);
      } catch (CloneNotSupportedException e) {
        // It should never happen.
        throw new IOException("Cannot clone ActiveFile object", e);
      }

      // Now perform the update
      File tmpMetaFile = null;
      if (!binfo.isInlineChecksum()) {
        // rename meta file to a tmp file
        tmpMetaFile = new File(oldMetaFile.getParent(),
            oldMetaFile.getName() + "_tmp" + newblock.getGenerationStamp());
        if (!oldMetaFile.renameTo(tmpMetaFile)) {
          throw new IOException("Cannot rename block meta file to " + tmpMetaFile);
        }
      }

      long oldBlockLength;
      if (!binfo.isInlineChecksum()) {
        oldBlockLength = blockFile.length();
      } else {
        oldBlockLength = BlockInlineChecksumReader.getBlockSizeFromFileLength(
            blockFile.length(), binfo.getChecksumType(),
            binfo.getBytesPerChecksum());
      }
      ActiveFile file = null;
      if (newblock.getNumBytes() < oldBlockLength) {
        if (!binfo.isInlineChecksum()) {
          new BlockWithChecksumFileWriter(binfo.getBlockDataFile(), tmpMetaFile)
            .truncateBlock(oldBlockLength, newblock.getNumBytes());
        } else {
          new BlockInlineChecksumWriter(binfo.getBlockDataFile(), binfo.getChecksumType(),
              binfo.getBytesPerChecksum(), datanode.writePacketSize)
            .truncateBlock(newblock.getNumBytes());
        }
        file = volumeMap.getOngoingCreates(namespaceId, oldblock);
        if (file != null) {
          file.setBytesAcked(newblock.getNumBytes());
          file.setBytesOnDisk(newblock.getNumBytes());
          file.setBytesReceived(newblock.getNumBytes());
        } else {
          // This should never happen unless called from unit tests.
          binfo.syncInMemorySize();
        }
      }

      String newDataFileName;
      if (!binfo.isInlineChecksum()) {
        //rename the tmp file to the new meta file (with new generation stamp)
        File newMetaFile = BlockWithChecksumFileWriter.getMetaFile(blockFile, newblock);
        if (!tmpMetaFile.renameTo(newMetaFile)) {
          throw new IOException("Cannot rename tmp meta file to " + newMetaFile);
        }
      } else {
        newDataFileName = BlockInlineChecksumWriter.getInlineChecksumFileName(
            newblock, binfo.getChecksumType(), binfo.getBytesPerChecksum());
        File newDataFile = new File(blockFile.getParent(), newDataFileName);
        if (!blockFile.renameTo(newDataFile)) {
          throw new IOException("Cannot rename data file to " + newDataFileName);
        }
        // fsyncIfPossible parent directory to persist rename.
        if (datanode.syncOnClose) {
          NativeIO.fsyncIfPossible(newDataFile.getParent());
        }
        setDataFileForBlock(namespaceId, oldblock, newDataFile);
      }
  
      if(volumeMap.getOngoingCreates(namespaceId, oldblock) != null){
        ActiveFile af = volumeMap.removeOngoingCreates(namespaceId, oldblock);
        volumeMap.addOngoingCreates(namespaceId, newblock, af);
      }
      volumeMap.update(namespaceId, oldblock, newblock);
  
      // paranoia! verify that the contents of the stored block 
      // matches the block file on disk.
      validateBlockMetadata(namespaceId, newblock);
      return null;
    } finally {
      lock.writeLock().unlock();
    }
  }
1016925
public static ThreadDump create()
  {
    ThreadDump threadDump = _threadDumpRef.get();
    
    if (threadDump == null) {
      threadDump = new ThreadDumpPro();
      
      _threadDumpRef.compareAndSet(null, threadDump);
      threadDump = _threadDumpRef.get();
    }
    
    return threadDump;
  }
1269346
@SuppressWarnings("unchecked")
    public T get() {
        if (HystrixRequestContext.getContextForCurrentThread() == null) {
            throw new IllegalStateException(HystrixRequestContext.class.getSimpleName() + ".initializeContext() must be called at the beginning of each request before RequestVariable functionality can be used.");
        }
        ConcurrentHashMap<HystrixRequestVariableDefault<?>, LazyInitializer<?>> variableMap = HystrixRequestContext.getContextForCurrentThread().state;

        // short-circuit the synchronized path below if we already have the value in the ConcurrentHashMap
        LazyInitializer<?> v = variableMap.get(this);
        if (v != null) {
            return (T) v.get();
        }

        /*
         * Optimistically create a LazyInitializer to put into the ConcurrentHashMap.
         * 
         * The LazyInitializer will not invoke initialValue() unless the get() method is invoked
         * so we can optimistically instantiate LazyInitializer and then discard for garbage collection
         * if the putIfAbsent fails.
         * 
         * Whichever instance of LazyInitializer succeeds will then have get() invoked which will call
         * the initialValue() method once-and-only-once.
         */
        LazyInitializer<T> l = new LazyInitializer<T>(this);
        LazyInitializer<?> existing = variableMap.putIfAbsent(this, l);
        if (existing == null) {
            /*
             * We won the thread-race so can use 'l' that we just created.
             */
            return l.get();
        } else {
            /*
             * We lost the thread-race so let 'l' be garbage collected and instead return 'existing'
             */
            return (T) existing.get();
        }
    }
96608
@Override
    public CauseOfBlockage getCauseOfBlockage() {
        // Block builds until they are done with post-production
        if (!isConcurrentBuild() && isLogUpdated()) {
            final R lastBuild = getLastBuild();
            if (lastBuild != null) {
                return new BlockedBecauseOfBuildInProgress(lastBuild);
            } else {
                // The build has been likely deleted after the isLogUpdated() call.
                // Another cause may be an API implementation glitсh in the implementation for AbstractProject. 
                // Anyway, we should let the code go then.
                LOGGER.log(Level.FINE, "The last build has been deleted during the non-concurrent cause creation. The build is not blocked anymore");
            }
        }
        if (blockBuildWhenDownstreamBuilding()) {
            AbstractProject<?,?> bup = getBuildingDownstream();
            if (bup!=null)
                return new BecauseOfDownstreamBuildInProgress(bup);
        }
        if (blockBuildWhenUpstreamBuilding()) {
            AbstractProject<?,?> bup = getBuildingUpstream();
            if (bup!=null)
                return new BecauseOfUpstreamBuildInProgress(bup);
        }
        return null;
    }
1070838
public static BegunTx<?> getBegunTxOnThread() {
        final Stack<BegunTx<?>> stack = threadLocal.get();
        return stack != null ? stack.peek() : null;
    }
854316
private ClientRWLock getBlockLock(long blockId) {
    // Loop until we either find the block lock in the mLocks map, or successfully acquire a new
    // block lock from the lock pool.
    while (true) {
      ClientRWLock blockLock;
      // Check whether a lock has already been allocated for the block id.
      synchronized (mSharedMapsLock) {
        blockLock = mLocks.get(blockId);
        if (blockLock != null) {
          blockLock.addReference();
          return blockLock;
        }
      }
      // Since a block lock hasn't already been allocated, try to acquire a new one from the pool.
      // Acquire the lock outside the synchronized section because #acquire might need to block.
      // We shouldn't wait indefinitely in acquire because the another lock for this block could be
      // allocated to another thread, in which case we could just use that lock.
      blockLock = mLockPool.acquire(1, TimeUnit.SECONDS);
      if (blockLock != null) {
        synchronized (mSharedMapsLock) {
          // Check if someone else acquired a block lock for blockId while we were acquiring one.
          if (mLocks.containsKey(blockId)) {
            mLockPool.release(blockLock);
            blockLock = mLocks.get(blockId);
          } else {
            mLocks.put(blockId, blockLock);
          }
          blockLock.addReference();
          return blockLock;
        }
      }
    }
  }
408690
public StoredBlock getCheckpointBefore(long time) {
        try {
            checkArgument(time > params.getGenesisBlock().getTimeSeconds());
            // This is thread safe because the map never changes after creation.
            Map.Entry<Long, StoredBlock> entry = checkpoints.floorEntry(time);
            if (entry != null) return entry.getValue();
            Block genesis = params.getGenesisBlock().cloneAsHeader();
            return new StoredBlock(genesis, genesis.getWork(), 0);
        } catch (VerificationException e) {
            throw new RuntimeException(e);  // Cannot happen.
        }
    }
92195
public function reorderBlocksAction()
	{
		$this->isPostRequest();
		$this->checkLock();

		$placeHolderName = $this->getRequestParameter('place_holder_id');

		$pageRequest = $this->createPageRequest();

		$placeHolder = $pageRequest->getPlaceHolderSet()
				->getFinalPlaceHolders()
				->offsetGet($placeHolderName);

		if ($placeHolder === null) {
			throw new \InvalidArgumentException(sprintf(
					'Placeholder [%s] not found in placeholders set.',
					$placeHolderName
			));
		}

		$blockSet = $pageRequest->getBlockSet()
				->getPlaceHolderBlockSet($placeHolder);

		$blockPositionMap = array_values($this->getRequestParameter('order', array()));

		if ($blockSet->count() !== count($blockPositionMap)) {
			// JS error or data spoofing
			throw new \UnexpectedValueException('Ordered elements and actual blocks count does not match.');
		}

		foreach ($blockPositionMap as $position => $id) {
			
			$block = $blockSet->findById($id);
			
			if ($block === null) {
				throw new \UnexpectedValueException(sprintf('Block [%s] not found.'));
			}

			$block->setPosition($position);
		}

		$this->getEntityManager()
				->flush();

		return new SupraJsonResponse();
	}
1134931
public @Nonnull SetType getBlockingThreads() {
        final ThreadType blocking = getBlockingThread();
        if (blocking == null) return runtime.getEmptyThreadSet();

        return runtime.getThreadSet(Collections.singleton(blocking));
    }
971135
public Buffer pin(BlockId blk) {
		// Try to find out if this block has been pinned by this transaction
		PinnedBuffer pinnedBuff = pinnedBuffers.get(blk);
		if (pinnedBuff != null) {
			pinnedBuff.pinnedCount++;
			return pinnedBuff.buffer;
		}
		
		// This transaction has pinned too many buffers
		if (pinnedBuffers.size() == BUFFER_POOL_SIZE)
			throw new BufferAbortException();
		
		// Pinning process
		try {
			Buffer buff;
			long timestamp = System.currentTimeMillis();
			boolean waitedBeforeGotBuffer = false;

			// Try to pin a buffer or the pinned buffer for the given BlockId
			buff = bufferPool.pin(blk);

			// If there is no such buffer or no available buffer,
			// wait for it
			if (buff == null) {
				waitedBeforeGotBuffer = true;
				synchronized (bufferPool) {
					waitingThreads.add(Thread.currentThread());

					while (buff == null && !waitingTooLong(timestamp)) {
						bufferPool.wait(MAX_TIME);
						if (waitingThreads.get(0).equals(Thread.currentThread()))
							buff = bufferPool.pin(blk);
					}

					waitingThreads.remove(Thread.currentThread());
				}
			}

			// If it still has no buffer after a long wait,
			// release and re-pin all buffers it has
			if (buff == null) {
				repin();
				buff = pin(blk);
			} else {
				pinnedBuffers.put(buff.block(), new PinnedBuffer(buff));
			}

			// TODO: Add some comment here
			if (waitedBeforeGotBuffer) {
				synchronized (bufferPool) {
					bufferPool.notifyAll();
				}
			}

			return buff;
		} catch (InterruptedException e) {
			throw new BufferAbortException();
		}
	}
1167579
public boolean abandonBlock(Block b, String src, String holder
  ) throws IOException {
    writeLock();
    try {
      //
      // Remove the block from the pending creates list
      //
      if (NameNode.stateChangeLog.isDebugEnabled()) {
        NameNode.stateChangeLog.debug("BLOCK* NameSystem.abandonBlock: "
          + b + "of file " + src);
      }
      if (isInSafeMode()) {
        throw new SafeModeException("Cannot abandon block " + b +
          " for fle" + src, safeMode);
      }
      INodeFileUnderConstruction file = checkLease(src, holder);
      dir.removeBlock(src, file, b);
      if (NameNode.stateChangeLog.isDebugEnabled()) {
        NameNode.stateChangeLog.debug("BLOCK* NameSystem.abandonBlock: "
          + b
          + " is removed from pendingCreates");
      }
      return true;
    } finally {
      writeUnlock();
    }
  }
462961
@Override
  public Block getPenultimateBlock() {
    if (blocks == null || blocks.length <= 1) {
      return null;
    }
    return blocks[blocks.length - 2];
  }
1060409
public BlockInfo updateINode(BlockInfo oldBlock, Block newBlock, INodeFile iNode,
      short replication, boolean forceUpdate) throws IOException {
    // If the old block is not same as the new block, probably the GS was
    // bumped up, hence update the block with new GS/size.
    // If forceUpdate is true, we will always remove the old block and 
    // update with new block, it's used by raid
    List<DatanodeDescriptor> locations = null;
    if (oldBlock != null && (!oldBlock.equals(newBlock) || forceUpdate)) {
      if (oldBlock.getBlockId() != newBlock.getBlockId()) {
        throw new IOException("block ids don't match : " + oldBlock + ", "
            + newBlock);
      }
      if (forceUpdate) {
        // save locations of the old block
        locations = new ArrayList<DatanodeDescriptor>();
        for (int i=0; i<oldBlock.numNodes(); i++) {
          locations.add(oldBlock.getDatanode(i));
        }
      } else {
        if (!iNode.isUnderConstruction()) {
          throw new IOException(
              "Try to update generation of a finalized block old block: "
                  + oldBlock + ", new block: " + newBlock);
        }
      }
      removeBlock(oldBlock);
    }
    BlockInfo info = checkBlockInfo(newBlock, replication);
    info.set(newBlock.getBlockId(), newBlock.getNumBytes(), newBlock.getGenerationStamp());
    info.inode = iNode;
    if (locations != null) {
      // add back the locations if needed
      if (locations != null) {
        for (DatanodeDescriptor d : locations) {
          d.addBlock(info);
        }
      }
    }
    return info;
  }
20112
synchronized boolean update() {
        int elected = this.elected;
        int oldelected = this.oldelected;
        int lbfactor = this.lbfactor;
        if (lbfactor > 0) {
            this.lbstatus = ((elected - oldelected) * 1000) / lbfactor;
        }
        this.oldelected = elected;
        return elected != oldelected; // ping if they are equal
    }
574976
public PostUpdate<Entity<T>> getOrCreatePostUpdate()
   {
      Node node = childNode.getOrCreate("post-update");
      PostUpdate<Entity<T>> postUpdate = new PostUpdateImpl<Entity<T>>(this, "post-update", childNode, node);
      return postUpdate;
   }
1066013
@Override public V get() {
    // check priorities - FJ task can only block on a task with higher priority!
    Thread cThr = Thread.currentThread();
    int priority = (cThr instanceof FJWThr) ? ((FJWThr)cThr)._priority : -1;
    assert _dt.priority() > priority || (_dt.priority() == priority && _dt instanceof MRTask)
      : "*** Attempting to block on task (" + _dt.getClass() + ") with equal or lower priority. Can lead to deadlock! " + _dt.priority() + " <=  " + priority;
    if( _done ) return result(); // Fast-path shortcut, or throw if exception
    // Use FJP ManagedBlock for this blocking-wait - so the FJP can spawn
    // another thread if needed.
    try { ForkJoinPool.managedBlock(this); } catch( InterruptedException ignore ) { }
    if( _done ) return result(); // Fast-path shortcut or throw if exception
    assert isCancelled();
    return null;
  }
1114513
public @Nonnull SetType getBlockedThreads() {
        Set<ThreadLock> acquired = new HashSet<ThreadLock>();
        for (ThreadType thread: threads) {
            acquired.addAll(thread.getAcquiredLocks());
        }

        Set<ThreadType> blocked = new HashSet<ThreadType>();
        for (ThreadType thread: runtime.getThreads()) {
            if (acquired.contains(thread.getWaitingToLock())) {
                blocked.add(thread);
            }
        }

        return runtime.getThreadSet(blocked);
    }