Wait for {@link #nextReadIndex} to be moved if necessary and move {@link #curWriteIndex}.
19165
private void increaseWriteIndex()
  {
    final long startAtNs = System.nanoTime();
    final long queryTimeoutAtNs = getQueryTimeoutAtNs(startAtNs);
    final long spinTimeoutAtNs = startAtNs + SPIN_FOR_TIMEOUT_THRESHOLD_NS;
    long timeoutNs = queryTimeoutAtNs - startAtNs;
    long spinTimeoutNs = SPIN_FOR_TIMEOUT_THRESHOLD_NS;

    // In the below, we check that the array is full and wait for at least one slot to become available.
    //
    // nextReadIndex is a volatile variable and the changes on it are continuously checked until they are seen in
    // the while loop. See the following links.
    // * http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.1.4
    // * http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4.5
    // * https://stackoverflow.com/questions/11761552/detailed-semantics-of-volatile-regarding-timeliness-of-visibility

    if (curWriteIndex == maxNumSlots - 1) {
      // We additionally check that nextReadIndex is -1 here because the writing thread should wait for the reading
      // thread to start reading only when the writing thread tries to overwrite the first slot for the first time.

      // The below condition is checked in a while loop instead of using a lock to avoid frequent thread park.
      while ((nextReadIndex == -1 || nextReadIndex == 0) && !Thread.currentThread().isInterrupted()) {
        if (timeoutNs <= 0L) {
          throw new RuntimeException(new TimeoutException());
        }
        // Thread.yield() should not be called from the very beginning
        if (spinTimeoutNs <= 0L) {
          Thread.yield();
        }
        long now = System.nanoTime();
        timeoutNs = queryTimeoutAtNs - now;
        spinTimeoutNs = spinTimeoutAtNs - now;
      }

      // Changes on nextReadIndex happens-before changing curWriteIndex.
      curWriteIndex = 0;
    } else {
      final int nextWriteIndex = curWriteIndex + 1;

      // The below condition is checked in a while loop instead of using a lock to avoid frequent thread park.
      while ((nextWriteIndex == nextReadIndex) && !Thread.currentThread().isInterrupted()) {
        if (timeoutNs <= 0L) {
          throw new RuntimeException(new TimeoutException());
        }
        // Thread.yield() should not be called from the very beginning
        if (spinTimeoutNs <= 0L) {
          Thread.yield();
        }
        long now = System.nanoTime();
        timeoutNs = queryTimeoutAtNs - now;
        spinTimeoutNs = spinTimeoutAtNs - now;
      }

      // Changes on nextReadIndex happens-before changing curWriteIndex.
      curWriteIndex = nextWriteIndex;
    }
  }
34708
public MtasSpanSequenceItem rewrite(IndexReader reader) throws IOException {
    MtasSpanQuery newSpanQuery = spanQuery.rewrite(reader);
    if (!newSpanQuery.equals(spanQuery)) {
      return new MtasSpanSequenceItem(newSpanQuery, optional);
    } else {
      return this;
    }
  }
197019
@Override
  public int positionedRead(long pos, byte[] b, int off, int len) throws IOException {
    return positionedReadInternal(pos, b, off, len);
  }
514198
@SuppressWarnings("unchecked")
  private void readNext() {
    // Compute the index of the next entry in the segment.
    final long index = getNextIndex();

    try {
      // Read more bytes from the segment if necessary.
      if (memory.remaining() < maxEntrySize) {
        long position = channel.position() + memory.position();
        channel.position(position);
        memory.clear();
        channel.read(memory);
        channel.position(position);
        memory.flip();
      }

      // Mark the buffer so it can be reset if necessary.
      memory.mark();

      try {
        // Read the length of the entry.
        final int length = memory.getInt();

        // If the buffer length is zero then return.
        if (length <= 0 || length > maxEntrySize) {
          memory.reset().limit(memory.position());
          nextEntry = null;
          return;
        }

        // Read the checksum of the entry.
        long checksum = memory.getInt() & 0xFFFFFFFFL;

        // Compute the checksum for the entry bytes.
        final Checksum crc32 = new CRC32();
        crc32.update(memory.array(), memory.position(), length);

        // If the stored checksum equals the computed checksum, return the entry.
        if (checksum == crc32.getValue()) {
          int limit = memory.limit();
          memory.limit(memory.position() + length);
          E entry = namespace.deserialize(memory);
          memory.limit(limit);
          nextEntry = new Indexed<>(index, entry, length);
        } else {
          memory.reset().limit(memory.position());
          nextEntry = null;
        }
      } catch (BufferUnderflowException e) {
        memory.reset().limit(memory.position());
        nextEntry = null;
      }
    } catch (IOException e) {
      throw new StorageException(e);
    }
  }
1081655
private synchronized void waitNextLoop(long ms) {
        try {
            wait(ms);
        } catch (InterruptedException e) {
            System.err.println(e);
        }
    }
1298913
@Override
  public int nextStartPosition() throws IOException {
    if (findMatches()) {
      currentMatch = queueMatches.get(0);
      queueMatches.remove(0);
      noMorePositions = false;
      return currentMatch.startPosition();
    } else {
      currentMatch = null;
      noMorePositions = true;
      return NO_MORE_POSITIONS;
    }
  }
877561
def next(self):
        
        while True:
            self.cur_idx += 1
            if self.__datasource.populate_iteration(self):
                return self

        raise StopIteration
1202957
public void startRead() {
		SynchronizationPoint<NoException> sp;
		synchronized (this) {
			if (!writer) {
				// nobody is writing, we can read
				readers++;
				return;
			}
			// if someone is writing, we need to wait
			if (readerWaiting == null)
				readerWaiting = new SynchronizationPoint<NoException>();
			sp = readerWaiting;
			readers++;
		}
		sp.block(0);
	}
1282442
public T next() {
		if(cachedNext == null) {
			throw new NoSuchElementException("call hasNext first!");
		}
		T o = cachedNext;
		cachedNext = null;
		return o;
	}
357814
@CheckForSigned
  private int _getReadIndex (final int key)
  {
    int idx = MapHelper.phiMix (key) & m_nMask;
    if (m_aKeys[idx] == key)
    {
      // we check FREE prior to this call
      return idx;
    }
    if (m_aKeys[idx] == FREE_KEY)
    {
      // end of chain already
      return -1;
    }
    final int startIdx = idx;
    while ((idx = _getNextIndex (idx)) != startIdx)
    {
      if (m_aKeys[idx] == FREE_KEY)
        return -1;
      if (m_aKeys[idx] == key)
        return idx;
    }
    return -1;
  }
1331431
@Override
	public boolean next() {
		if (isLhsEmpty)
			return false;
		if (idx.next()) {
			ts.moveToRecordId(idx.getDataRecordId());
			return true;
		} else if (!(isLhsEmpty = !s.next())) {
			resetIndex();
			return next();
		} else
			return false;
	}
317590
public void advance() {
        String s = null;
        if (baseIterator.hasNext())
            next = baseIterator.next();
        else
            next = null;
    }
102588
private boolean acquireWriteFuture(int sliceLength) {
        if (sliceLength > 0) {
            Object writeResult = null;
            // determine a good timeout value based on the slice length to write
            int timeout = sliceLength * 500;
            // check for existing future
            if (writerFuture != null) {
                try {
                    // wait for a result from the last writer
                    writeResult = writerFuture.get(timeout, TimeUnit.MILLISECONDS);
                } catch (Exception e) {
                    log.warn("Exception waiting for write result. Timeout: {}ms", timeout, e);
                    return false;
                }
            }
            log.debug("Write future result (expect null): {}", writeResult);
            return true;
        }
        return false;
    }
855882
@Nullable
  public ICommonsList <String> readNext () throws IOException
  {
    ICommonsList <String> ret = null;
    do
    {
      final String sNextLine = _getNextLine ();
      if (!m_bHasNext)
      {
        // should throw if still pending?
        return ret;
      }
      final ICommonsList <String> r = m_aParser.parseLineMulti (sNextLine);
      if (ret == null)
        ret = r;
      else
        ret.addAll (r);
    } while (m_aParser.isPending ());
    return ret;
  }
284365
public void setCurrentIndex(int index) {

    // yes, index == getLength() is allowed - that is the state when the end is reached and
    // setCurrentIndex(getCurrentPosition()) should NOT cause an exception...
    if ((index < 0) || (index > getLength())) {
      throw new IndexOutOfBoundsException(Integer.toString(index));
    }
    this.offset = this.initialOffset + index;
  }
131113
private void pauseOrResumeReading() {
        int bytesWaiting;
        synchronized (lock) {
            bytesWaiting = waitingAppends.values()
                    .stream()
                    .mapToInt(a -> a.getData().readableBytes())
                    .sum();
        }

        if (bytesWaiting > HIGH_WATER_MARK) {
            log.debug("Pausing writing from connection {}", connection);
            connection.pauseReading();
        }
        if (bytesWaiting < LOW_WATER_MARK) {
            log.trace("Resuming writing from connection {}", connection);
            connection.resumeReading();
        }
    }
829124
private void advance() {
        try {
            // loop until we find a word in the reader, or there are no more
            // words
            while (true) {
                // if we haven't looked at any lines yet, or if the index into
                // the current line is already at the end 
                if (curLine == null || !matcher.find()) {

                    String line = br.readLine();
                    
                    // if there aren't any more lines in the reader, then mark
                    // next as null to indicate that there are no more words
                    if (line == null) {
                        next = null;
                        br.close();
                        return;
                    }
                    
                    // create a new matcher to find all the tokens in this line
                    matcher = notWhiteSpace.matcher(line);
                    curLine = line;
                    
                    // skip lines with no matches
                    if (!matcher.find())
                        continue;                    
                }

                next = curLine.substring(matcher.start(), matcher.end());
                break;
            }
        } catch (IOException ioe) {
            throw new IOError(ioe);
        }
    }