Example usage for java.nio ByteBuffer allocateDirect

List of usage examples for java.nio ByteBuffer allocateDirect

Introduction

In this page you can find the example usage for java.nio ByteBuffer allocateDirect.

Prototype

public static ByteBuffer allocateDirect(int capacity) 

Source Link

Document

Creates a direct byte buffer based on a newly allocated memory block.

Usage

From source file:com.alvermont.terraj.fracplanet.geom.TriangleBufferArray.java

/**
 * Resize this buffer to accomodate a larger number of elements
 *///from w  ww .  j  av  a  2s  .  c om
protected void resizeBuffer() {
    // we can't resize it so we have to allocate a new one and copy the data across
    final int slots = this.buffer.capacity() / INTS_PER_ENTRY;
    final int newCapacity = this.buffer.capacity()
            + (((slots * CAPACITY_PCT_INCREASE) / PERCENT_100) * INTS_PER_ENTRY);

    final IntBuffer newBuffer = ByteBuffer.allocateDirect(newCapacity * SIZEOF_INT)
            .order(ByteOrder.nativeOrder()).asIntBuffer();

    newBuffer.limit(this.buffer.limit());

    if (log.isDebugEnabled()) {
        log.debug("Resizing triangle buffer capacity to: " + newCapacity + " " + newBuffer.capacity());
    }

    this.buffer.rewind();
    newBuffer.put(this.buffer);

    this.buffer = newBuffer;
}

From source file:org.apache.hadoop.io.compress.lzo.LzoCompressor.java

/** 
 * Creates a new compressor using the specified {@link CompressionStrategy}.
 * /*from ww  w.  j  a v  a  2  s  .  c  om*/
 * @param strategy lzo compression algorithm to use
 * @param directBufferSize size of the direct buffer to be used.
 */
public LzoCompressor(CompressionStrategy strategy, int directBufferSize) {
    this.strategy = strategy;
    this.directBufferSize = directBufferSize;
    uncompressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize);
    compressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize);
    compressedDirectBuf.position(directBufferSize);

    /**
     * Initialize {@link #lzoCompress} and {@link #workingMemoryBufLen}
     */
    init(this.strategy.getCompressor());
    workingMemoryBuf = ByteBuffer.allocateDirect(workingMemoryBufLen);
}

From source file:xbird.server.services.RemotePagingService.java

private void acceptConnections(final ServerSocketChannel channel) throws IOException {
    // set to non blocking mode
    channel.configureBlocking(false);//from  w w w . jav a  2  s . c o m

    // Bind the server socket to the local host and port
    InetAddress host = InetAddress.getLocalHost();
    InetSocketAddress sockAddr = new InetSocketAddress(host, PORT);
    ServerSocket socket = channel.socket();
    //socket.setReuseAddress(true);
    socket.bind(sockAddr);

    // Register accepts on the server socket with the selector. This
    // step tells the selector that the socket wants to be put on the
    // ready list when accept operations occur.
    Selector selector = Selector.open();

    ByteBuffer cmdBuffer = ByteBuffer.allocateDirect(MAX_COMMAND_BUFLEN);
    IOHandler ioHandler = new IOHandler(cmdBuffer);
    AcceptHandler acceptHandler = new AcceptHandler(ioHandler);

    channel.register(selector, SelectionKey.OP_ACCEPT, acceptHandler);

    int n;
    while ((n = selector.select()) > 0) {
        // Someone is ready for I/O, get the ready keys
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        final Iterator<SelectionKey> keyItor = selectedKeys.iterator();
        while (keyItor.hasNext()) {
            SelectionKey key = keyItor.next();
            keyItor.remove();
            // The key indexes into the selector so you
            // can retrieve the socket that's ready for I/O
            Handler handler = (Handler) key.attachment();
            try {
                handler.handle(key);
            } catch (CancelledKeyException cke) {
                ;
            } catch (IOException ioe) {
                LOG.fatal(ioe);
                NIOUtils.cancelKey(key);
            } catch (Throwable e) {
                LOG.fatal(e);
                NIOUtils.cancelKey(key);
            }
        }
    }
}

From source file:org.mhisoft.common.util.FileUtils.java

/**
 * @param source/*from   w ww . j  a  v a 2  s .com*/
 * @param target
 * @throws IOException
 */
public static void copyFile(final File source, final File target) throws IOException {
    FileChannel in = null;
    FileChannel out = null;
    //   long totalFileSize = 0;

    try {
        in = new FileInputStream(source).getChannel();
        out = new FileOutputStream(target).getChannel();
        //totalFileSize = in.size();

        ByteBuffer buffer = ByteBuffer.allocateDirect(BUFFER);
        int readSize = in.read(buffer);
        long totalRead = 0;
        //int progress = 0;

        //long startTime, endTime  ;

        while (readSize != -1) {

            //startTime = System.currentTimeMillis();
            totalRead = totalRead + readSize;

            //progress = (int) (totalRead * 100 / totalFileSize);

            buffer.flip();

            while (buffer.hasRemaining()) {
                out.write(buffer);
                //System.out.printf(".");
                //showPercent(rdProUI, totalSize/size );
            }
            buffer.clear();
            readSize = in.read(buffer);

            //endTime = System.currentTimeMillis();
        }

    } finally {
        close(in);
        close(out);

    }
}

From source file:org.nd4j.linalg.jcublas.buffer.BaseCudaDataBuffer.java

@Override
protected void setNioBuffer() {
    wrappedBuffer = ByteBuffer.allocateDirect(elementSize * length);
    wrappedBuffer.order(ByteOrder.nativeOrder());
}

From source file:gobblin.util.io.StreamUtilsTest.java

@Test
public void testRegularByteBufferToStream() throws IOException {
    final int BUF_LEN = 128000;
    Random random = new Random();
    byte[] srcBytes = new byte[BUF_LEN];
    random.nextBytes(srcBytes);//from  w  w  w .j  a v  a2 s.c  om

    // allocate a larger size than we actually use to make sure we don't copy off the end of the used portion of the
    // buffer
    ByteBuffer buffer = ByteBuffer.allocate(BUF_LEN * 2);
    verifyBuffer(srcBytes, buffer);

    // now try with direct buffers; they aren't array backed so codepath is different
    buffer = ByteBuffer.allocateDirect(BUF_LEN * 2);
    verifyBuffer(srcBytes, buffer);
}

From source file:org.apache.hadoop.hbase.io.ByteBufferPool.java

/**
 * @return One free ByteBuffer from the pool. If no free ByteBuffer and we have not reached the
 *         maximum pool size, it will create a new one and return. In case of max pool size also
 *         reached, will return null. When pool returned a ByteBuffer, make sure to return it back
 *         to pool after use./*  w  ww .j a  va 2s. c  o m*/
 * @see #putbackBuffer(ByteBuffer)
 */
public ByteBuffer getBuffer() {
    ByteBuffer bb = buffers.poll();
    if (bb != null) {
        // Clear sets limit == capacity. Position == 0.
        bb.clear();
        return bb;
    }
    while (true) {
        int c = this.count.intValue();
        if (c >= this.maxPoolSize) {
            if (maxPoolSizeInfoLevelLogged) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Pool already reached its max capacity : " + this.maxPoolSize
                            + " and no free buffers now. Consider increasing the value for '"
                            + MAX_POOL_SIZE_KEY + "' ?");
                }
            } else {
                LOG.info("Pool already reached its max capacity : " + this.maxPoolSize
                        + " and no free buffers now. Consider increasing the value for '" + MAX_POOL_SIZE_KEY
                        + "' ?");
                maxPoolSizeInfoLevelLogged = true;
            }
            return null;
        }
        if (!this.count.compareAndSet(c, c + 1)) {
            continue;
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("Creating a new offheap ByteBuffer of size: " + this.bufferSize);
        }
        return this.directByteBuffer ? ByteBuffer.allocateDirect(this.bufferSize)
                : ByteBuffer.allocate(this.bufferSize);
    }
}

From source file:com.google.android.apps.body.LayersLoader.java

private static ShortBuffer decodeVertexBuffer(DrawGroup drawGroup, char[] data, int start, int length) {
    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(length * 2);
    byteBuffer.order(ByteOrder.nativeOrder());
    ShortBuffer vertexData = byteBuffer.asShortBuffer();
    short prev0 = 0, prev1 = 0, prev2 = 0, prev3 = 0;
    short prev4 = 0, prev5 = 0, prev6 = 0, prev7 = 0;
    for (int i = 0; i < length;) {
        int limit = Math.min(length - i, BUFSIZE);
        int s = start + i;
        for (int j = 0; j < limit;) {
            short word = (short) data[s + j];
            prev0 += (word >> 1) ^ (-(word & 1));
            mBuffer[j++] = (short) (prev0 - 8192);
            word = (short) data[s + j];
            prev1 += (word >> 1) ^ (-(word & 1));
            mBuffer[j++] = (short) (prev1 - 4096);
            word = (short) data[s + j];
            prev2 += (word >> 1) ^ (-(word & 1));
            mBuffer[j++] = (short) (prev2 - 8192);
            word = (short) data[s + j];
            prev3 += (word >> 1) ^ (-(word & 1));
            mBuffer[j++] = (short) ((prev3 - 256) << 7);
            word = (short) data[s + j];
            prev4 += (word >> 1) ^ (-(word & 1));
            mBuffer[j++] = (short) ((prev4 - 256) << 7);
            word = (short) data[s + j];
            prev5 += (word >> 1) ^ (-(word & 1));
            mBuffer[j++] = (short) ((prev5 - 256) << 7);
            word = (short) data[s + j];
            prev6 += (word >> 1) ^ (-(word & 1));
            mBuffer[j++] = (short) prev6;
            word = (short) data[s + j];
            prev7 += (word >> 1) ^ (-(word & 1));
            // The web version flips the tex images instead.
            mBuffer[j++] = (short) (512 - prev7);
        }//from w  ww.  ja v  a2s.c om
        i += limit;
        vertexData.put(mBuffer, 0, limit);
    }
    vertexData.rewind();

    return vertexData;
}

From source file:com.gpl_compression.lzo.LzoCompressor.java

/**
 * Reallocates a direct byte buffer by freeing the old one and allocating
 * a new one, unless the size is the same, in which case it is simply
 * cleared and returned.//  www  . j a  va2 s.  c o m
 *
 * NOTE: this uses unsafe APIs to manually free memory - if anyone else
 * has a reference to the 'buf' parameter they will likely read random
 * data or cause a segfault by accessing it.
 */
private ByteBuffer realloc(ByteBuffer buf, int newSize) {
    if (buf != null) {
        if (buf.capacity() == newSize) {
            // Can use existing buffer
            buf.clear();
            return buf;
        }
        try {
            // Manually free the old buffer using undocumented unsafe APIs.
            // If this fails, we'll drop the reference and hope GC finds it
            // eventually.
            Object cleaner = buf.getClass().getMethod("cleaner").invoke(buf);
            cleaner.getClass().getMethod("clean").invoke(cleaner);
        } catch (Exception e) {
            // Perhaps a non-sun-derived JVM - contributions welcome
            LOG.warn("Couldn't realloc bytebuffer", e);
        }
    }
    return ByteBuffer.allocateDirect(newSize);
}

From source file:com.chicm.cmraft.rpc.PacketUtils.java

public static RpcCall parseRpcResponseFromChannel(AsynchronousSocketChannel channel, BlockingService service)
        throws InterruptedException, ExecutionException, IOException {
    RpcCall call = null;/*from  www.j a  v a  2 s. c  om*/
    long t = System.currentTimeMillis();
    InputStream in = Channels.newInputStream(channel);
    byte[] datasize = new byte[MESSAGE_LENGHT_FIELD_SIZE];
    in.read(datasize);
    int nDataSize = bytes2Int(datasize);

    LOG.debug("message size: " + nDataSize);

    int len = 0;
    ByteBuffer buf = ByteBuffer.allocateDirect(nDataSize);
    for (; len < nDataSize;) {
        len += channel.read(buf).get();
    }
    if (len < nDataSize) {
        LOG.error("SOCKET READ FAILED, len:" + len);
        return call;
    }
    byte[] data = new byte[nDataSize];
    buf.flip();
    buf.get(data);
    int offset = 0;
    CodedInputStream cis = CodedInputStream.newInstance(data, offset, nDataSize - offset);
    int headerSize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();
    ResponseHeader header = ResponseHeader.newBuilder().mergeFrom(data, offset, headerSize).build();

    offset += headerSize;
    cis.skipRawBytes(headerSize);
    cis.resetSizeCounter();
    int bodySize = cis.readRawVarint32();
    offset += cis.getTotalBytesRead();

    MethodDescriptor md = service.getDescriptorForType().findMethodByName(header.getResponseName());
    Builder builder = service.getResponsePrototype(md).newBuilderForType();
    Message body = null;
    if (builder != null) {
        body = builder.mergeFrom(data, offset, bodySize).build();
    }
    call = new RpcCall(header.getId(), header, body, md);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Parse Rpc response from socket: " + call.getCallId() + ", takes"
                + (System.currentTimeMillis() - t) + " ms");
    }

    return call;
}