Java Code Examples for java.nio.ByteBuffer.isDirect()

The following are Jave code examples for showing how to use isDirect() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: sstable-adaptor   File: ChannelProxy.java   View Source Code Vote up 6 votes
public int read(ByteBuffer buffer, long position)
{
    int size = 0;
    byte[] temBuff = null;

    try {
        if (buffer.isDirect()) {
            //TODO: have a better way to allocate this using thread local or pooling
            temBuff = new byte[buffer.capacity()];
            size = read(position, temBuff, 0, buffer.limit());
            buffer.put(temBuff, 0, size);
        } else {
            temBuff = buffer.array();
            size = read(position, temBuff, 0, buffer.limit());
            buffer.limit(buffer.capacity());
            buffer.position(size);
        }
        return size;
    } catch (IOException e) {
        throw new FSReadError(e, filePath.getName());
    }
}
 
Example 2
Project: Elasticsearch   File: Channels.java   View Source Code Vote up 6 votes
/**
 * Writes a {@link java.nio.ByteBuffer} to a {@link java.nio.channels.WritableByteChannel}
 *
 * @param byteBuffer source buffer
 * @param channel    channel to write to
 */
public static void writeToChannel(ByteBuffer byteBuffer, WritableByteChannel channel) throws IOException {
    if (byteBuffer.isDirect() || (byteBuffer.remaining() <= WRITE_CHUNK_SIZE)) {
        while (byteBuffer.hasRemaining()) {
            channel.write(byteBuffer);
        }
    } else {
        // duplicate the buffer in order to be able to change the limit
        ByteBuffer tmpBuffer = byteBuffer.duplicate();
        try {
            while (byteBuffer.hasRemaining()) {
                tmpBuffer.limit(Math.min(byteBuffer.limit(), tmpBuffer.position() + WRITE_CHUNK_SIZE));
                while (tmpBuffer.hasRemaining()) {
                    channel.write(tmpBuffer);
                }
                byteBuffer.position(tmpBuffer.position());
            }
        } finally {
            // make sure we update byteBuffer to indicate how far we came..
            byteBuffer.position(tmpBuffer.position());
        }
    }
}
 
Example 3
Project: sstable-adaptor   File: MemoryUtil.java   View Source Code Vote up 5 votes
public static void setBytes(long address, ByteBuffer buffer)
{
    int start = buffer.position();
    int count = buffer.limit() - start;
    if (count == 0)
        return;

    if (buffer.isDirect())
        setBytes(((DirectBuffer)buffer).address() + start, address, count);
    else
        setBytes(address, buffer.array(), buffer.arrayOffset() + start, count);
}
 
Example 4
Project: OpenJSharp   File: SocketOrChannelConnectionImpl.java   View Source Code Vote up 5 votes
public ByteBuffer read(ByteBuffer byteBuffer, int offset,
                       int length, long max_wait_time)
    throws IOException
{
    int size = offset + length;
    if (shouldUseDirectByteBuffers()) {

        if (! byteBuffer.isDirect()) {
            throw wrapper.unexpectedNonDirectByteBufferWithChannelSocket();
        }
        if (size > byteBuffer.capacity()) {
            if (orb.transportDebugFlag) {
                // print address of ByteBuffer being released
                int bbAddress = System.identityHashCode(byteBuffer);
                StringBuffer bbsb = new StringBuffer(80);
                bbsb.append(".read: releasing ByteBuffer id (")
                    .append(bbAddress).append(") to ByteBufferPool.");
                String bbmsg = bbsb.toString();
                dprint(bbmsg);
            }
            orb.getByteBufferPool().releaseByteBuffer(byteBuffer);
            byteBuffer = orb.getByteBufferPool().getByteBuffer(size);
        }
        byteBuffer.position(offset);
        byteBuffer.limit(size);
        readFully(byteBuffer, length, max_wait_time);
        byteBuffer.position(0);
        byteBuffer.limit(size);
        return byteBuffer;
    }
    if (byteBuffer.isDirect()) {
        throw wrapper.unexpectedDirectByteBufferWithNonChannelSocket();
    }
    byte[] buf = new byte[size];
    readFully(getSocket().getInputStream(), buf,
              offset, length, max_wait_time);
    return ByteBuffer.wrap(buf);
}
 
Example 5
Project: ditb   File: KeyValueUtil.java   View Source Code Vote up 5 votes
/**
 * Creates a new KeyValue object positioned in the supplied ByteBuffer and sets the ByteBuffer's
 * position to the start of the next KeyValue. Does not allocate a new array or copy data.
 * @param bb
 * @param includesMvccVersion
 * @param includesTags
 */
public static KeyValue nextShallowCopy(final ByteBuffer bb, final boolean includesMvccVersion,
    boolean includesTags) {
  if (bb.isDirect()) {
    throw new IllegalArgumentException("only supports heap buffers");
  }
  if (bb.remaining() < 1) {
    return null;
  }
  KeyValue keyValue = null;
  int underlyingArrayOffset = bb.arrayOffset() + bb.position();
  int keyLength = bb.getInt();
  int valueLength = bb.getInt();
  ByteBufferUtils.skip(bb, keyLength + valueLength);
  int tagsLength = 0;
  if (includesTags) {
    // Read short as unsigned, high byte first
    tagsLength = ((bb.get() & 0xff) << 8) ^ (bb.get() & 0xff);
    ByteBufferUtils.skip(bb, tagsLength);
  }
  int kvLength = (int) KeyValue.getKeyValueDataStructureSize(keyLength, valueLength, tagsLength);
  keyValue = new KeyValue(bb.array(), underlyingArrayOffset, kvLength);
  if (includesMvccVersion) {
    long mvccVersion = ByteBufferUtils.readVLong(bb);
    keyValue.setSequenceId(mvccVersion);
  }
  return keyValue;
}
 
Example 6
Project: hadoop   File: DomainSocket.java   View Source Code Vote up 5 votes
@Override
public int read(ByteBuffer dst) throws IOException {
  refCount.reference();
  boolean exc = true;
  try {
    int nread = 0;
    if (dst.isDirect()) {
      nread = DomainSocket.readByteBufferDirect0(DomainSocket.this.fd,
          dst, dst.position(), dst.remaining());
    } else if (dst.hasArray()) {
      nread = DomainSocket.readArray0(DomainSocket.this.fd,
          dst.array(), dst.position() + dst.arrayOffset(),
          dst.remaining());
    } else {
      throw new AssertionError("we don't support " +
          "using ByteBuffers that aren't either direct or backed by " +
          "arrays");
    }
    if (nread > 0) {
      dst.position(dst.position() + nread);
    }
    exc = false;
    return nread;
  } finally {
    unreference(exc);
  }
}
 
Example 7
Project: openjdk-jdk10   File: ModulePatcher.java   View Source Code Vote up 5 votes
@Override
public void release(ByteBuffer bb) {
    if (bb.isDirect()) {
        try {
            delegate().release(bb);
        } catch (IOException ioe) {
            throw new InternalError(ioe);
        }
    }
}
 
Example 8
Project: s-store   File: NIOWriteStream.java   View Source Code Vote up 5 votes
/**
 * Used for assertions. Returns false if one of the buffers is not direct
 * @param buffers
 * @return
 */
private final boolean checkAllDirect(final ByteBuffer buffers[]) {
    for (final ByteBuffer b : buffers ) {
       if (!b.isDirect()) {
           return false;
       }
    }
    return true;
}
 
Example 9
Project: BiglyBT   File: SHA1.java   View Source Code Vote up 5 votes
/**
 * Starts or continues a SHA-1 message digest calculation.
 * Only the remaining bytes of the given ByteBuffer are used.
 * @param buffer input data
 */
public void update(ByteBuffer buffer) {
	length += buffer.remaining();
	//Save current position to leave given buffer unchanged
	int position = buffer.position();

	//Complete the final buffer if needed
	completeFinalBuffer(buffer);

	if(!buffer.hasArray() || buffer.isDirect())
	{
		if(cacheBlock == null) // only allocate if we process direct byte buffers
			cacheBlock = new byte[cacheSize];
		while(buffer.remaining() >= 64)
		{
			int toProcess = Math.min(buffer.remaining()-buffer.remaining()%64,cacheSize);
			buffer.get(cacheBlock, 0, toProcess);
			for(int i = 0;i < toProcess; i+=64)
				transform(cacheBlock,i);
		}
	} else // use direct array access for heap buffers
	{
		final int endPos = buffer.position()+buffer.remaining()-buffer.remaining()%64;
		final int internalEndPos = endPos+buffer.arrayOffset();
		for(int i = buffer.arrayOffset()+buffer.position();i < internalEndPos;i+=64)
			transform(buffer.array(),i);
		buffer.position(endPos);
	}


	if(buffer.remaining() != 0) {
		finalBuffer.put(buffer);
	}

	buffer.position(position);
}
 
Example 10
Project: monarch   File: UnsafeAccess.java   View Source Code Vote up 5 votes
/**
 * Put an int value out to the specified ByteBuffer offset in big-endian format.
 * 
 * @param buf the ByteBuffer to write to
 * @param offset offset in the ByteBuffer
 * @param val int to write out
 * @return incremented offset
 */
public static int putInt(ByteBuffer buf, int offset, int val) {
  if (littleEndian) {
    val = Integer.reverseBytes(val);
  }
  if (buf.isDirect()) {
    theUnsafe.putInt(((DirectBuffer) buf).address() + offset, val);
  } else {
    theUnsafe.putInt(buf.array(), offset + buf.arrayOffset() + BYTE_ARRAY_BASE_OFFSET, val);
  }
  return offset + Bytes.SIZEOF_INT;
}
 
Example 11
Project: monarch   File: UnsafeAccess.java   View Source Code Vote up 5 votes
/**
 * Returns the byte at the given offset
 * 
 * @param buf the buffer to read
 * @param offset the offset at which the byte has to be read
 * @return the byte at the given offset
 */
public static byte toByte(ByteBuffer buf, int offset) {
  if (buf.isDirect()) {
    return theUnsafe.getByte(((DirectBuffer) buf).address() + offset);
  } else {
    return theUnsafe.getByte(buf.array(), BYTE_ARRAY_BASE_OFFSET + buf.arrayOffset() + offset);
  }
}
 
Example 12
Project: monarch   File: UnsafeAccess.java   View Source Code Vote up 5 votes
/**
 * Copies specified number of bytes from given offset of {@code src} ByteBuffer to the
 * {@code dest} array.
 *
 * @param src
 * @param srcOffset
 * @param dest
 * @param destOffset
 * @param length
 */
public static void copy(ByteBuffer src, int srcOffset, byte[] dest, int destOffset, int length) {
  long srcAddress = srcOffset;
  Object srcBase = null;
  if (src.isDirect()) {
    srcAddress = srcAddress + ((DirectBuffer) src).address();
  } else {
    srcAddress = srcAddress + BYTE_ARRAY_BASE_OFFSET + src.arrayOffset();
    srcBase = src.array();
  }
  long destAddress = destOffset + BYTE_ARRAY_BASE_OFFSET;
  unsafeCopy(srcBase, srcAddress, dest, destAddress, length);
}
 
Example 13
Project: monarch   File: UnsafeAccess.java   View Source Code Vote up 5 votes
/**
 * Put a byte value out to the specified BB position in big-endian format.
 * 
 * @param buf the byte buffer
 * @param offset position in the buffer
 * @param b byte to write out
 * @return incremented offset
 */
public static int putByte(ByteBuffer buf, int offset, byte b) {
  if (buf.isDirect()) {
    theUnsafe.putByte(((DirectBuffer) buf).address() + offset, b);
  } else {
    theUnsafe.putByte(buf.array(), BYTE_ARRAY_BASE_OFFSET + buf.arrayOffset() + offset, b);
  }
  return offset + 1;
}
 
Example 14
Project: hadoop   File: BlockReaderLocal.java   View Source Code Vote up 4 votes
/**
 * Read using the bounce buffer.
 *
 * A 'direct' read actually has three phases. The first drains any
 * remaining bytes from the slow read buffer. After this the read is
 * guaranteed to be on a checksum chunk boundary. If there are still bytes
 * to read, the fast direct path is used for as many remaining bytes as
 * possible, up to a multiple of the checksum chunk size. Finally, any
 * 'odd' bytes remaining at the end of the read cause another slow read to
 * be issued, which involves an extra copy.
 *
 * Every 'slow' read tries to fill the slow read buffer in one go for
 * efficiency's sake. As described above, all non-checksum-chunk-aligned
 * reads will be served from the slower read path.
 *
 * @param buf              The buffer to read into. 
 * @param canSkipChecksum  True if we can skip checksums.
 */
private synchronized int readWithBounceBuffer(ByteBuffer buf,
      boolean canSkipChecksum) throws IOException {
  int total = 0;
  int bb = drainDataBuf(buf); // drain bounce buffer if possible
  if (bb >= 0) {
    total += bb;
    if (buf.remaining() == 0) return total;
  }
  boolean eof = true, done = false;
  do {
    if (buf.isDirect() && (buf.remaining() >= maxReadaheadLength)
          && ((dataPos % bytesPerChecksum) == 0)) {
      // Fast lane: try to read directly into user-supplied buffer, bypassing
      // bounce buffer.
      int oldLimit = buf.limit();
      int nRead;
      try {
        buf.limit(buf.position() + maxReadaheadLength);
        nRead = fillBuffer(buf, canSkipChecksum);
      } finally {
        buf.limit(oldLimit);
      }
      if (nRead < maxReadaheadLength) {
        done = true;
      }
      if (nRead > 0) {
        eof = false;
      }
      total += nRead;
    } else {
      // Slow lane: refill bounce buffer.
      if (fillDataBuf(canSkipChecksum)) {
        done = true;
      }
      bb = drainDataBuf(buf); // drain bounce buffer if possible
      if (bb >= 0) {
        eof = false;
        total += bb;
      }
    }
  } while ((!done) && (buf.remaining() > 0));
  return (eof && total == 0) ? -1 : total;
}
 
Example 15
Project: hadoop-oss   File: AbstractRawErasureDecoder.java   View Source Code Vote up 4 votes
@Override
public void decode(ByteBuffer[] inputs, int[] erasedIndexes,
                   ByteBuffer[] outputs) {
  checkParameters(inputs, erasedIndexes, outputs);

  ByteBuffer validInput = CoderUtil.findFirstValidInput(inputs);
  boolean usingDirectBuffer = validInput.isDirect();
  int dataLen = validInput.remaining();
  if (dataLen == 0) {
    return;
  }
  checkParameterBuffers(inputs, true, dataLen, usingDirectBuffer, false);
  checkParameterBuffers(outputs, false, dataLen, usingDirectBuffer, true);

  int[] inputPositions = new int[inputs.length];
  for (int i = 0; i < inputPositions.length; i++) {
    if (inputs[i] != null) {
      inputPositions[i] = inputs[i].position();
    }
  }

  if (usingDirectBuffer) {
    doDecode(inputs, erasedIndexes, outputs);
  } else {
    int[] inputOffsets = new int[inputs.length];
    int[] outputOffsets = new int[outputs.length];
    byte[][] newInputs = new byte[inputs.length][];
    byte[][] newOutputs = new byte[outputs.length][];

    ByteBuffer buffer;
    for (int i = 0; i < inputs.length; ++i) {
      buffer = inputs[i];
      if (buffer != null) {
        inputOffsets[i] = buffer.arrayOffset() + buffer.position();
        newInputs[i] = buffer.array();
      }
    }

    for (int i = 0; i < outputs.length; ++i) {
      buffer = outputs[i];
      outputOffsets[i] = buffer.arrayOffset() + buffer.position();
      newOutputs[i] = buffer.array();
    }

    doDecode(newInputs, inputOffsets, dataLen,
        erasedIndexes, newOutputs, outputOffsets);
  }

  for (int i = 0; i < inputs.length; i++) {
    if (inputs[i] != null) {
      // dataLen bytes consumed
      inputs[i].position(inputPositions[i] + dataLen);
    }
  }
}
 
Example 16
Project: reading-and-annotate-rocketmq-3.4.6   File: MapedFile.java   View Source Code Vote up 4 votes
public static void clean(final ByteBuffer buffer) {
    if (buffer == null || !buffer.isDirect() || buffer.capacity() == 0)
        return;
    invoke(invoke(viewed(buffer), "cleaner"), "clean");
}
 
Example 17
Project: monarch   File: UnsafeAccess.java   View Source Code Vote up 3 votes
/**
 * Reads bytes at the given offset as a long value.
 * 
 * @param buf
 * @param offset
 * @return long value at offset
 */
static long getAsLong(ByteBuffer buf, int offset) {
  if (buf.isDirect()) {
    return theUnsafe.getLong(((DirectBuffer) buf).address() + offset);
  }
  return theUnsafe.getLong(buf.array(), BYTE_ARRAY_BASE_OFFSET + buf.arrayOffset() + offset);
}
 
Example 18
Project: hadoop-oss   File: NativeIO.java   View Source Code Vote up 3 votes
/**
 * Locks the provided direct ByteBuffer into memory, preventing it from
 * swapping out. After a buffer is locked, future accesses will not incur
 * a page fault.
 * 
 * See the mlock(2) man page for more information.
 * 
 * @throws NativeIOException
 */
static void mlock(ByteBuffer buffer, long len)
    throws IOException {
  assertCodeLoaded();
  if (!buffer.isDirect()) {
    throw new IOException("Cannot mlock a non-direct ByteBuffer");
  }
  mlock_native(buffer, len);
}
 
Example 19
Project: big_data   File: NativeIOaa.java   View Source Code Vote up 3 votes
/**
 * Locks the provided direct ByteBuffer into memory, preventing it from
 * swapping out. After a buffer is locked, future accesses will not
 * incur a page fault.
 * 
 * See the mlock(2) man page for more information.
 * 
 * @throws NativeIOException
 */
static void mlock(ByteBuffer buffer, long len) throws IOException {
	assertCodeLoaded();
	if (!buffer.isDirect()) {
		throw new IOException("Cannot mlock a non-direct ByteBuffer");
	}
	mlock_native(buffer, len);
}
 
Example 20
Project: monarch   File: UnsafeAccess.java   View Source Code Vote up 3 votes
/**
 * Reads bytes at the given offset as a short value.
 * 
 * @param buf
 * @param offset
 * @return short value at offset
 */
static short getAsShort(ByteBuffer buf, int offset) {
  if (buf.isDirect()) {
    return theUnsafe.getShort(((DirectBuffer) buf).address() + offset);
  }
  return theUnsafe.getShort(buf.array(), BYTE_ARRAY_BASE_OFFSET + buf.arrayOffset() + offset);
}