java.nio.ByteBuffer#isDirect ( )源码实例Demo

下面列出了java.nio.ByteBuffer#isDirect ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: aion-germany   文件: BufferUtils.java
/**
 * Creates a new ByteBuffer with the same contents as the given ByteBuffer. The new ByteBuffer is seperate from the old one and changes are not reflected across. If you want to reflect changes,
 * consider using Buffer.duplicate().
 *
 * @param buf
 *            the ByteBuffer to copy
 * @return the copy
 */
public static ByteBuffer clone(ByteBuffer buf) {
	if (buf == null) {
		return null;
	}
	buf.rewind();

	ByteBuffer copy;
	if (buf.isDirect()) {
		copy = createByteBuffer(buf.limit());
	}
	else {
		copy = ByteBuffer.allocate(buf.limit());
	}
	copy.put(buf);

	return copy;
}
 
源代码2 项目: bloomfilter   文件: MMapFileBackedBitArray.java
/**
 * Method that helps unmap a memory-mapped file before being
 * garbage-collected.
 * 
 * @param cb
 */
protected void closeDirectBuffer(ByteBuffer cb) {
    if (!cb.isDirect()) {
    	return;
    }

    // we could use this type cast and call functions without reflection code,
    // but static import from sun.* package is risky for non-SUN virtual machine.
    //try { ((sun.nio.ch.DirectBuffer)cb).cleaner().clean(); } catch (Exception ex) { }
    try {
        Method cleaner = cb.getClass().getMethod("cleaner");
        cleaner.setAccessible(true);
        Method clean = Class.forName("sun.misc.Cleaner").getMethod("clean");
        clean.setAccessible(true);
        clean.invoke(cleaner.invoke(cb));
    } catch(Exception ex) { 
    	
    }
    
    cb = null;
}
 
源代码3 项目: AsyncSocket   文件: ByteBufferReader.java
public byte[] getAllByteArray() {
    // fast path to return the contents of the first and only byte buffer,
    // if that's what we're looking for. avoids allocation.
    if (mBuffers.size() == 1) {
        ByteBuffer peek = mBuffers.peek();
        if (peek.capacity() == remaining() && peek.isDirect()) {
            remaining = 0;
            return mBuffers.remove().array();
        }
    }

    byte[] ret = new byte[remaining()];
    get(ret);

    return ret;
}
 
源代码4 项目: steamworks4j   文件: SteamUser.java
public int initiateGameConnection(ByteBuffer authBlob, SteamID steamIDGameServer,
								  int serverIP, short serverPort, boolean secure) throws SteamException {

	if (!authBlob.isDirect()) {
		throw new SteamException("Direct buffer required!");
	}

	int bytesWritten = initiateGameConnection(pointer, authBlob, authBlob.position(), authBlob.remaining(),
			steamIDGameServer.handle, serverIP, serverPort, secure);

	if (bytesWritten > 0) {
		authBlob.limit(bytesWritten);
	}

	return bytesWritten;
}
 
源代码5 项目: agrona   文件: UnsafeBuffer.java
public void wrap(final ByteBuffer buffer, final int offset, final int length)
{
    if (SHOULD_BOUNDS_CHECK)
    {
        boundsCheckWrap(offset, length, buffer.capacity());
    }

    if (buffer != byteBuffer)
    {
        byteBuffer = buffer;
    }

    if (buffer.isDirect())
    {
        byteArray = null;
        addressOffset = address(buffer) + offset;
    }
    else
    {
        byteArray = array(buffer);
        addressOffset = ARRAY_BASE_OFFSET + arrayOffset(buffer) + offset;
    }

    capacity = length;
}
 
源代码6 项目: Telegram   文件: FlacDecoderJni.java
/** Decodes and consumes the next sample from the FLAC stream into the given byte buffer. */
@SuppressWarnings("ByteBufferBackingArray")
public void decodeSample(ByteBuffer output)
    throws IOException, InterruptedException, FlacFrameDecodeException {
  output.clear();
  int frameSize =
      output.isDirect()
          ? flacDecodeToBuffer(nativeDecoderContext, output)
          : flacDecodeToArray(nativeDecoderContext, output.array());
  if (frameSize < 0) {
    if (!isDecoderAtEndOfInput()) {
      throw new FlacFrameDecodeException("Cannot decode FLAC frame", frameSize);
    }
    // The decoder has read to EOI. Return a 0-size frame to indicate the EOI.
    output.limit(0);
  } else {
    output.limit(frameSize);
  }
}
 
源代码7 项目: Bytecoder   文件: Deflater.java
/**
 * Sets preset dictionary for compression. A preset dictionary is used
 * when the history buffer can be predetermined. When the data is later
 * uncompressed with Inflater.inflate(), Inflater.getAdler() can be called
 * in order to get the Adler-32 value of the dictionary required for
 * decompression.
 * <p>
 * The bytes in given byte buffer will be fully consumed by this method.  On
 * return, its position will equal its limit.
 *
 * @param dictionary the dictionary data bytes
 * @see Inflater#inflate
 * @see Inflater#getAdler
 */
public void setDictionary(ByteBuffer dictionary) {
    synchronized (zsRef) {
        int position = dictionary.position();
        int remaining = Math.max(dictionary.limit() - position, 0);
        ensureOpen();
        if (dictionary.isDirect()) {
            long address = ((DirectBuffer) dictionary).address();
            try {
                setDictionaryBuffer(zsRef.address(), address + position, remaining);
            } finally {
                Reference.reachabilityFence(dictionary);
            }
        } else {
            byte[] array = ZipUtils.getBufferArray(dictionary);
            int offset = ZipUtils.getBufferOffset(dictionary);
            setDictionary(zsRef.address(), array, offset + position, remaining);
        }
        dictionary.position(position + remaining);
    }
}
 
源代码8 项目: xian   文件: PoolingGelfMessage.java
private void gzip(ByteBuffer source, ReusableGzipOutputStream gz) throws IOException {
    int size = source.position();

    if (source.isDirect()) {

        int read = 0;
        source.position(0);

        byte[] bytes = poolHolder.getByteArray();
        while (size > read) {

            if ((size - read) > bytes.length) {
                read += bytes.length;
                source.get(bytes);
                gz.write(bytes);
            } else {
                int remain = size - read;
                read += remain;
                source.get(bytes, 0, remain);
                gz.write(bytes, 0, remain);
            }
        }
    } else {
        gz.write(source.array(), source.arrayOffset(), source.position());
    }
}
 
源代码9 项目: jbrotli   文件: BrotliDeCompressor.java
/**
 * One may use {@link ByteBuffer#position(int)} and {@link ByteBuffer#limit(int)} to adjust
 * how the buffers are used for reading and writing.
 *
 * @param in  compressed input
 * @param out output buffer
 * @return output buffer length
 * @throws BrotliException in case of something in native code went wrong
 */
public final int deCompress(ByteBuffer in, ByteBuffer out) throws BrotliException {
  int inPosition = in.position();
  int inLimit = in.limit();
  int inRemain = inLimit - inPosition;
  if (inRemain <= 0)
    throw new IllegalArgumentException("The source (in) position must me smaller then the source ByteBuffer's limit.");

  int outPosition = out.position();
  int outLimit = out.limit();
  int outRemain = outLimit - outPosition;
  if (outRemain <= 0)
    throw new IllegalArgumentException("The destination (out) position must me smaller then the source ByteBuffer's limit.");

  int outLength;
  if (in.isDirect() && out.isDirect()) {
    outLength = assertBrotliOk(deCompressByteBuffer(in, inPosition, inRemain, out, outPosition, outRemain));
  } else if (in.hasArray() && out.hasArray()) {
    outLength = assertBrotliOk(deCompressBytes(in.array(), inPosition + in.arrayOffset(), inRemain, out.array(), outPosition + out.arrayOffset(), outRemain));
  } else {
    throw new UnsupportedOperationException("Not supported ByteBuffer implementation. Both (input and output) buffer has to be of the same type. Use either direct BB or wrapped byte arrays. You may raise an issue on GitHub too ;-)");
  }
  in.position(inLimit);
  out.limit(outPosition + outLength);
  return outLength;
}
 
源代码10 项目: hottub   文件: SocketOrChannelConnectionImpl.java
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);
}
 
源代码11 项目: ArrowExample   文件: ArrowOutputStream.java
@Override
public int write(ByteBuffer src) throws IOException {
    if(src.isDirect()){
        return writeDirectBuffer(src);
    } else {
        return writeHeapBuffer(src);
    }
}
 
源代码12 项目: epoll   文件: ByteBufferWrapper.java
public ByteBufferWrapper(ByteBuffer buffer) {
    if (!buffer.isDirect())
        throw new IllegalArgumentException("byte buffer must be direct");

    this.buffer = buffer;
    address = EpollCore.address(buffer);
}
 
源代码13 项目: jdk8u60   文件: SocketOrChannelConnectionImpl.java
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);
}
 
源代码14 项目: openjdk-8   文件: SocketOrChannelConnectionImpl.java
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);
}
 
源代码15 项目: hbase   文件: UnsafeAccess.java
/**
 * Reads bytes at the given offset as an int value.
 * @param buf
 * @param offset
 * @return int value at offset
 */
static int getAsInt(ByteBuffer buf, int offset) {
  if (buf.isDirect()) {
    return theUnsafe.getInt(((DirectBuffer) buf).address() + offset);
  }
  return theUnsafe.getInt(buf.array(), BYTE_ARRAY_BASE_OFFSET + buf.arrayOffset() + offset);
}
 
源代码16 项目: stratio-cassandra   文件: MemoryUtil.java
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(unsafe.getLong(buffer, DIRECT_BYTE_BUFFER_ADDRESS_OFFSET) + start, address, count);
    else
        setBytes(address, buffer.array(), buffer.arrayOffset() + start, count);
}
 
源代码17 项目: rocketmq-all-4.1.0-incubating   文件: MappedFile.java
public static void clean(final ByteBuffer buffer) {
    if (buffer == null || !buffer.isDirect() || buffer.capacity() == 0)
        return;
    invoke(invoke(viewed(buffer), "cleaner"), "clean");
}
 
源代码18 项目: steamworks4j   文件: SteamUtils.java
public boolean getImageRGBA(int image, ByteBuffer dest) throws SteamException {
	if (!dest.isDirect()) {
		throw new SteamException("Direct buffer required!");
	}
	return getImageRGBA(pointer, image, dest, dest.position(), dest.remaining());
}
 
源代码19 项目: ShizuruNotes   文件: Dictionary.java
public static void setData(ByteBuffer data) {
  if (!data.isDirect() || !data.isReadOnly()) {
    throw new BrotliRuntimeException("data must be a direct read-only byte buffer");
  }
  Dictionary.data = data;
}
 
源代码20 项目: openjdk-jdk8u   文件: ByteBufferPoolImpl.java
public void releaseByteBuffer(ByteBuffer thebb)
{
    if (thebb.isDirect())
    {
        synchronized (itsPool)
        {
            // use with debug to determine if byteBuffer is already
            // in the pool.
            boolean refInPool = false;
            int bbAddr = 0;

            if (debug)
            {
                // Check to make sure we don't have 'thebb' reference
                // already in the pool before adding it.

                for (int i = 0; i < itsPool.size() && refInPool == false; i++)
                {
                     ByteBuffer tmpbb = (ByteBuffer)itsPool.get(i);
                     if (thebb == tmpbb)
                     {
                         refInPool = true;
                         bbAddr = System.identityHashCode(thebb);
                     }
                }

            }

            // NOTE: The else part of this if will only get called
            //       if debug = true and refInPool = true, see logic above.
            if (refInPool == false || debug == false)
            {
                // add ByteBuffer back to the pool
                itsPool.add(thebb);
            }
            else // otherwise, log a stack trace with duplicate message
            {
                String threadName = Thread.currentThread().getName();
                Throwable t =
                        new Throwable(threadName +
                                     ": Duplicate ByteBuffer reference (" +
                                     bbAddr + ")");
                t.printStackTrace(System.out);
            }
        }

        // decrement the count of ByteBuffers released
        // IMPORTANT: Since this counter is used only for information
        //            purposes, it does not use synchronized access.
        itsObjectCounter--;
    }
    else
    {
        // ByteBuffer not pooled nor needed
        thebb = null;
    }
}