Drains the read buffer up to an amortized threshold.
770897
@GuardedBy("evictionLock")
    void drainWriteBuffer() {
        for (int i = 0; i < WRITE_BUFFER_DRAIN_THRESHOLD; i++) {
            final Runnable task = writeBuffer.poll();
            if (task == null) {
                break;
            }
            task.run();
        }
    }
1208320
def __cleanup(self):
        
# TODO: Test this.
        with self.__class__.__locker:

            while self.__read_buffer_index > 0:
                del self.__buffers[0]
                self.__read_buffer_index -= 1
1145319
public static void clearToFill(ByteBuffer buffer) {
        if (buffer != null) {
            buffer.position(0);
            buffer.limit(buffer.capacity());
        }
    }
9489
@Override
    public void releaseBuffer ( byte[] buf ) {
        // better safe than sorry: prevent leaks if there is some out of bound access
        Arrays.fill(buf, (byte) 0);
        synchronized ( this.cache ) {
            if ( this.freeBuffers < this.cache.length ) {
                for ( int i = 0; i < this.cache.length; i++ ) {
                    if ( this.cache[ i ] == null ) {
                        this.cache[ i ] = buf;
                        this.freeBuffers++;
                        return;
                    }
                }
            }
        }
    }
2614
void drainBuffers() {
        // A mostly strict ordering is achieved by observing that each buffer
        // contains tasks in a weakly sorted order starting from the last drain.
        // The buffers can be merged into a sorted array in O(n) time by using
        // counting sort and chaining on a collision.

        // Moves the tasks into the output array, applies them, and updates the
        // marker for the starting order of the next drain.
        int maxTaskIndex = moveTasksFromBuffers(tasks);
        updateDrainedOrder(tasks, maxTaskIndex);
        runTasks(tasks, maxTaskIndex);
    }
17386
public void defrag() {

        if (cacheReadonly) {
            return;
        }

        if (fileFreePosition == INITIAL_FREE_POS) {
            return;
        }

        database.logger.appLog.logContext(SimpleLog.LOG_NORMAL, "start");

        try {
            boolean wasNio = dataFile.wasNio();

            cache.saveAll();

            DataFileDefrag dfd = new DataFileDefrag(database, this, fileName);

            dfd.process();
            close(false);
            deleteFile(wasNio);
            renameDataFile(wasNio);
            backupFile();
            database.getProperties().setProperty(
                HsqlDatabaseProperties.hsqldb_cache_version,
                HsqlDatabaseProperties.THIS_CACHE_VERSION);
            database.getProperties().save();
            cache.clear();

            cache = new Cache(this);

            open(cacheReadonly);
            dfd.updateTableIndexRoots();
            dfd.updateTransactionRowIDs();
        } catch (Throwable e) {
            database.logger.appLog.logContext(e, null);

            if (e instanceof HsqlException) {
                throw (HsqlException) e;
            } else {
                throw new HsqlException(
                    e, Error.getMessage(ErrorCode.GENERAL_IO_ERROR),
                    ErrorCode.GENERAL_IO_ERROR);
            }
        }

        database.logger.appLog.logContext(SimpleLog.LOG_NORMAL, "end");
    }
699417
public void flushBuffer() throws IOException {
        if (mCompressedSegments != 0) {
            throw new IOException("cannot flush a compressed buffer");
        }
        
        // marked the stream as having been previously flushed to avoid
        // attempting to compress the stream after the fact
        mFlushed = true;
        
        // write the internal buffer to the output stream and then clear any
        // data in the internal buffer to avoid duplicated data.
        ByteBuffer bytes = mBuffer;
        OutputStream out = super.getOutputStream();
        bytes.writeTo(out);
        bytes.clear();
        
        super.flushBuffer();
    }
95821
void reset(int hashTableSize, int capacity) {
        // A VoltDB extension to diagnose ArrayOutOfBounds.
        if (linkTable != null) {
            voltDBresetCapacity = linkTable.length;
        }
        ++voltDBresetCount;
        voltDBlastResetEvent = voltDBhistoryDepth;
        voltDBhistoryCapacity = Math.min(voltDBhistoryMaxCapacity, 
                                         Math.max(voltDBhistoryMinCapacity, voltDBhistoryDepth));
        voltDBhistory = new int[voltDBhistoryCapacity];
        // End of VoltDB extension

        int[] newHT = new int[hashTableSize];
        int[] newLT = new int[capacity];

        // allocate memory before assigning
        hashTable = newHT;
        linkTable = newLT;

        resetTables();
    }
447600
def __clear_in_buffer(self):
        
        self.__in_buffer.value = bytes(b'\0' * len(self.__in_buffer))
178606
private final void flushBuffer() throws IOException {
		if (bufOutput.position() > 0) {
			bufOutput.flip();
			fcOutput.write(bufOutput);
			bufOutput.clear();
			// log.debug("offsetOutputUncommited=" + offsetOutputUncommited + " offsetOutputCommited=" +
			// offsetOutputCommited + " fcOutput.position()=" + fcOutput.position());
			offsetOutputUncommited = offsetOutputCommited = fcOutput.position();
			if (syncOnFlush) {
				fcOutput.force(false);
				if (callback != null) {
					callback.synched(offsetOutputCommited);
				}
			}
		}
	}
936953
protected void read() throws IOException {
        buffer.rewind();
        buffer.limit(buffer.capacity());
        device.read(offset, buffer);
        this.dirty = false;
    }
36571
public void clear() {
		//release a static buffer if possible
		if (_buffersToReuse != null && !_buffersToReuse.isEmpty()) {
			StaticBuffers.getInstance().releaseByteBuffer(BUFFER_KEY, _buffersToReuse.peek());
		} else if (!_buffers.isEmpty()) {
			StaticBuffers.getInstance().releaseByteBuffer(BUFFER_KEY, _buffers.get(0));
		}
		
		if (_buffersToReuse != null) {
			_buffersToReuse.clear();
		}
		_buffers.clear();
		_position = 0;
		_flushPosition = 0;
		_size = 0;
	}
1172875
void flushBuffer() throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (nextChar == 0)
                return;
            out.write(cb, 0, nextChar);
            nextChar = 0;
        }
    }
816398
private void cleanupDecBuffers() {
        // if we have decrypted buffers and they are either JIT created or made
        // during decryption/expansion (user buffers too small) then release them
        // here and dereference
        if (null != this.decryptedNetBuffers
            && (callerRequiredAllocation || decryptedNetBufferReleaseRequired)) {
            WsByteBufferUtils.releaseBufferArray(this.decryptedNetBuffers);
            this.decryptedNetBuffers = null;
        }
    }
273562
private void handleReads(final MemcachedNode node) throws IOException {
    Operation currentOp = node.getCurrentReadOp();
    if (currentOp instanceof TapAckOperationImpl) {
      node.removeCurrentReadOp();
      return;
    }

    ByteBuffer rbuf = node.getRbuf();
    final SocketChannel channel = node.getChannel();
    int read = channel.read(rbuf);
    metrics.updateHistogram(OVERALL_AVG_BYTES_READ_METRIC, read);
    if (read < 0) {
      currentOp = handleReadsWhenChannelEndOfStream(currentOp, node, rbuf);
    }

    while (read > 0) {
      getLogger().debug("Read %d bytes", read);
      rbuf.flip();
      while (rbuf.remaining() > 0) {
        if (currentOp == null) {
          throw new IllegalStateException("No read operation.");
        }

        long timeOnWire =
          System.nanoTime() - currentOp.getWriteCompleteTimestamp();
        metrics.updateHistogram(OVERALL_AVG_TIME_ON_WIRE_METRIC,
          (int)(timeOnWire / 1000));
        metrics.markMeter(OVERALL_RESPONSE_METRIC);
        synchronized(currentOp) {
          readBufferAndLogMetrics(currentOp, rbuf, node);
        }

        currentOp = node.getCurrentReadOp();
      }
      rbuf.clear();
      read = channel.read(rbuf);
      node.completedRead();
    }
  }
614314
protected void flushCacheWithAppend(byte[] bufferToAppend, int off, int len) throws IOException {
        byte[] chunkHeader = (Integer.toHexString(cachePosition + len) + "\r\n").getBytes(StandardCharsets.US_ASCII);
        stream.write(chunkHeader, 0, chunkHeader.length);
        stream.write(cache, 0, cachePosition);
        stream.write(bufferToAppend, off, len);
        stream.write(ENDCHUNK, 0, ENDCHUNK.length);
        cachePosition = 0;
    }
391650
protected void ensureAvailableBytes(int amount) throws IOException {
		if (!this.seekEnabled && amount > this.buffer.remaining()) {
			this.bufferPosition += this.buffer.position();
			this.buffer.compact();
			int limit = this.buffer.position();
			final int read = this.stream.read(this.buffer);
			if (read < 0) {
				if (limit == 0) {
					throw new EOFException();
				}
			} else {
				limit += read;
			}
			this.buffer.rewind();
			this.buffer.limit(limit);

		}
		if (amount > this.buffer.remaining()) {
			throw new EOFException();
		}
	}