Class ByteBuffer
- All Implemented Interfaces:
Comparable<ByteBuffer>
- Direct Known Subclasses:
BaseByteBuffer
,ByteBufferProxy
This is a replacement for ByteBuffer
. Please refer to
ByteBuffer
and Buffer
documentation for
usage. MINA does not use NIO ByteBuffer
directly for two
reasons:
- It doesn't provide useful getters and putters such as
fill
,get/putString
, andget/putAsciiInt()
enough. - It is hard to distinguish if the buffer is created from MINA buffer pool or not. MINA have to return used buffers back to pool.
- It is difficult to write variable-length data due to its fixed capacity
Allocation
You can get a heap buffer from buffer pool:
ByteBuffer buf = ByteBuffer.allocate(1024, false);you can also get a direct buffer from buffer pool:
ByteBuffer buf = ByteBuffer.allocate(1024, true);or you can let MINA choose:
ByteBuffer buf = ByteBuffer.allocate(1024);
Acquire/Release
Please note that you never need to release the allocated buffer because MINA will release it automatically when:
- You pass the buffer by calling
IoSession.write(Object)
. - You pass the buffer by calling
IoFilter.NextFilter.filterWrite(IoSession,IoFilter.WriteRequest)
. - You pass the buffer by calling
ProtocolEncoderOutput.write(ByteBuffer)
.
ByteBuffer
which is passed as a parameter
of IoHandler.messageReceived(IoSession, Object)
method. They are released
automatically when the method returns.
You have to release buffers manually by calling release()
when:
- You allocated a buffer, but didn't pass the buffer to any of two methods above.
- You called
acquire()
to prevent the buffer from being released.
Wrapping existing NIO buffers and arrays
This class provides a few wrap(...) methods that wraps
any NIO buffers and byte arrays. Wrapped MINA buffers are not returned
to the buffer pool by default to prevent unexpected memory leakage by default.
In case you want to make it pooled, you can call setPooled(boolean)
with true flag to enable pooling.
AutoExpand
Writing variable-length data using NIO ByteBuffers is not really
easy, and it is because its size is fixed. MINA ByteBuffer
introduces autoExpand property. If autoExpand property
is true, you never get BufferOverflowException
or
IndexOutOfBoundsException
(except when index is negative).
It automatically expands its capacity and limit value. For example:
String greeting = messageBundle.getMessage( "hello" ); ByteBuffer buf = ByteBuffer.allocate( 16 ); // Turn on autoExpand (it is off by default) buf.setAutoExpand( true ); buf.putString( greeting, utf8encoder );NIO ByteBuffer is reallocated by MINA ByteBuffer behind the scene if the encoded data is larger than 16 bytes. Its capacity and its limit will increase to the last position the string is written.
Derived Buffers
Derived buffers are the buffers which were created by
duplicate()
, slice()
, or asReadOnlyBuffer()
.
They are useful especially when you broadcast the same messages to
multiple IoSession
s. Please note that the derived buffers are
neither pooled nor auto-expandable. Trying to expand a derived buffer will
raise IllegalStateException
.
Changing Buffer Allocation and Management Policy
MINA provides a ByteBufferAllocator
interface to let you override
the default buffer management behavior. There are two allocators provided
out-of-the-box:
setAllocator(ByteBufferAllocator)
.
- See Also:
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionabstract void
acquire()
Increases the internal reference count of this buffer to defer automatic release.static ByteBuffer
allocate
(int capacity) Returns the direct or heap buffer which is capable of the specified size.static ByteBuffer
allocate
(int capacity, boolean direct) Returns the buffer which is capable of the specified size.abstract byte[]
array()
abstract int
abstract CharBuffer
abstract DoubleBuffer
abstract FloatBuffer
Returns anInputStream
that reads the data from this buffer.abstract IntBuffer
abstract LongBuffer
Returns anOutputStream
that appends the data into this buffer.abstract ByteBuffer
abstract ShortBuffer
protected ByteBuffer
autoExpand
(int expectedRemaining) This method forwards the call toexpand(int)
only when autoExpand property is true.protected ByteBuffer
autoExpand
(int pos, int expectedRemaining) This method forwards the call toexpand(int)
only when autoExpand property is true.abstract ByteBuffer
buf()
Returns the underlying NIO buffer instance.abstract int
capacity()
abstract ByteBuffer
capacity
(int newCapacity) Changes the capacity of this buffer.abstract ByteBuffer
clear()
abstract ByteBuffer
compact()
int
compareTo
(ByteBuffer that) abstract ByteBuffer
boolean
expand
(int expectedRemaining) Changes the capacity and limit of this buffer so this buffer get the specified expectedRemaining room from the current position.abstract ByteBuffer
expand
(int pos, int expectedRemaining) Changes the capacity and limit of this buffer so this buffer get the specified expectedRemaining room from the specified pos.fill
(byte value, int size) Fills this buffer with the specified value.fill
(int size) Fills this buffer withNUL (0x00)
.fillAndReset
(byte value, int size) Fills this buffer with the specified value.fillAndReset
(int size) Fills this buffer withNUL (0x00)
.abstract ByteBuffer
flip()
abstract byte
get()
get
(byte[] dst) abstract ByteBuffer
get
(byte[] dst, int offset, int length) abstract byte
get
(int index) static ByteBufferAllocator
Returns the current allocator which manages the allocated buffers.abstract char
getChar()
abstract char
getChar
(int index) abstract double
abstract double
getDouble
(int index) abstract float
getFloat()
abstract float
getFloat
(int index) Returns hexdump of this buffer.abstract int
getInt()
abstract int
getInt
(int index) abstract long
getLong()
abstract long
getLong
(int index) Reads a Java object from the buffer using the contextClassLoader
of the current thread.getObject
(ClassLoader classLoader) Reads a Java object from the buffer using the specified classLoader.getPrefixedString
(int prefixLength, CharsetDecoder decoder) Reads a string which has a length field before the actual encoded string, using the specifieddecoder
and returns it.getPrefixedString
(CharsetDecoder decoder) Reads a string which has a 16-bit length field before the actual encoded string, using the specifieddecoder
and returns it.abstract short
getShort()
abstract short
getShort
(int index) getString
(int fieldSize, CharsetDecoder decoder) Reads aNUL
-terminated string from this buffer using the specifieddecoder
and returns it.getString
(CharsetDecoder decoder) Reads aNUL
-terminated string from this buffer using the specifieddecoder
and returns it.short
Reads one unsigned byte as a short integer.short
getUnsigned
(int index) Reads one byte as an unsigned short integer.long
Reads four bytes unsigned integer.long
getUnsignedInt
(int index) Reads four bytes unsigned integer.int
Reads two bytes unsigned integer.int
getUnsignedShort
(int index) Reads two bytes unsigned integer.int
hashCode()
boolean
abstract boolean
Returns true if and only if autoExpand is turned on.abstract boolean
isDirect()
abstract boolean
isPooled()
Returns true if and only if this buffer is returned back to the buffer pool when released.abstract boolean
static boolean
abstract int
limit()
abstract ByteBuffer
limit
(int newLimit) abstract ByteBuffer
mark()
abstract int
Returns the position of the current mark.abstract ByteOrder
order()
abstract ByteBuffer
abstract int
position()
abstract ByteBuffer
position
(int newPosition) boolean
prefixedDataAvailable
(int prefixLength) Returns true if this buffer contains a data which has a data length as a prefix and the buffer has remaining data as enough as specified in the data length field.boolean
prefixedDataAvailable
(int prefixLength, int maxDataLength) Returns true if this buffer contains a data which has a data length as a prefix and the buffer has remaining data as enough as specified in the data length field.abstract ByteBuffer
put
(byte b) put
(byte[] src) abstract ByteBuffer
put
(byte[] src, int offset, int length) abstract ByteBuffer
put
(int index, byte b) abstract ByteBuffer
put
(ByteBuffer src) Writes the content of the specified src into this buffer.put
(ByteBuffer src) Writes the content of the specified src into this buffer.abstract ByteBuffer
putChar
(char value) abstract ByteBuffer
putChar
(int index, char value) abstract ByteBuffer
putDouble
(double value) abstract ByteBuffer
putDouble
(int index, double value) abstract ByteBuffer
putFloat
(float value) abstract ByteBuffer
putFloat
(int index, float value) abstract ByteBuffer
putInt
(int value) abstract ByteBuffer
putInt
(int index, int value) abstract ByteBuffer
putLong
(int index, long value) abstract ByteBuffer
putLong
(long value) Writes the specified Java object to the buffer.putPrefixedString
(CharSequence val, int prefixLength, int padding, byte padValue, CharsetEncoder encoder) Writes the content ofin
into this buffer as a string which has a 16-bit length field before the actual encoded string, using the specifiedencoder
.putPrefixedString
(CharSequence in, int prefixLength, int padding, CharsetEncoder encoder) Writes the content ofin
into this buffer as a string which has a 16-bit length field before the actual encoded string, using the specifiedencoder
.putPrefixedString
(CharSequence in, int prefixLength, CharsetEncoder encoder) Writes the content ofin
into this buffer as a string which has a 16-bit length field before the actual encoded string, using the specifiedencoder
.putPrefixedString
(CharSequence in, CharsetEncoder encoder) Writes the content ofin
into this buffer as a string which has a 16-bit length field before the actual encoded string, using the specifiedencoder
.abstract ByteBuffer
putShort
(int index, short value) abstract ByteBuffer
putShort
(short value) putString
(CharSequence val, int fieldSize, CharsetEncoder encoder) Writes the content ofin
into this buffer as aNUL
-terminated string using the specifiedencoder
.putString
(CharSequence val, CharsetEncoder encoder) Writes the content ofin
into this buffer using the specifiedencoder
.abstract void
release()
Releases the specified buffer to buffer pool.int
abstract ByteBuffer
reset()
abstract ByteBuffer
rewind()
static void
setAllocator
(ByteBufferAllocator newAllocator) Changes the current allocator with the specified one to manage the allocated buffers from now.abstract ByteBuffer
setAutoExpand
(boolean autoExpand) Turns on or off autoExpand.abstract void
setPooled
(boolean pooled) Sets whether this buffer is returned back to the buffer pool when released.static void
setUseDirectBuffers
(boolean useDirectBuffers) skip
(int size) Forwards the position of this buffer as the specifiedsize
bytes.abstract ByteBuffer
slice()
sweep()
Clears this buffer and fills its content with NUL.sweep
(byte value) Clears this buffer and fills its content with value.toString()
static ByteBuffer
wrap
(byte[] byteArray) Wraps the specified byte array into MINA heap buffer.static ByteBuffer
wrap
(byte[] byteArray, int offset, int length) Wraps the specified byte array into MINA heap buffer.static ByteBuffer
wrap
(ByteBuffer nioBuffer) Wraps the specified NIOByteBuffer
into MINA buffer.
-
Constructor Details
-
ByteBuffer
protected ByteBuffer()
-
-
Method Details
-
getAllocator
Returns the current allocator which manages the allocated buffers. -
setAllocator
Changes the current allocator with the specified one to manage the allocated buffers from now. -
isUseDirectBuffers
public static boolean isUseDirectBuffers() -
setUseDirectBuffers
public static void setUseDirectBuffers(boolean useDirectBuffers) -
allocate
Returns the direct or heap buffer which is capable of the specified size. This method tries to allocate direct buffer first, and then tries heap buffer if direct buffer memory is exhausted. Please useallocate(int, boolean)
to allocate buffers of specific type.- Parameters:
capacity
- the capacity of the buffer
-
allocate
Returns the buffer which is capable of the specified size.- Parameters:
capacity
- the capacity of the bufferdirect
- true to get a direct buffer, false to get a heap buffer.
-
wrap
Wraps the specified NIOByteBuffer
into MINA buffer. -
wrap
Wraps the specified byte array into MINA heap buffer. -
wrap
Wraps the specified byte array into MINA heap buffer. Please note that MINA buffers are going to be pooled, and therefore there can be waste of memory if you wrap your byte array specifying offset and length. -
acquire
public abstract void acquire()Increases the internal reference count of this buffer to defer automatic release. You have to invokerelease()
as many as you invoked this method to release this buffer.- Throws:
IllegalStateException
- if you attempt to acquire already released buffer.
-
release
public abstract void release()Releases the specified buffer to buffer pool.- Throws:
IllegalStateException
- if you attempt to release already released buffer.
-
buf
Returns the underlying NIO buffer instance. -
isDirect
public abstract boolean isDirect()- See Also:
-
isReadOnly
public abstract boolean isReadOnly()- See Also:
-
capacity
public abstract int capacity()- See Also:
-
capacity
Changes the capacity of this buffer. -
isAutoExpand
public abstract boolean isAutoExpand()Returns true if and only if autoExpand is turned on. -
setAutoExpand
Turns on or off autoExpand. -
expand
Changes the capacity and limit of this buffer so this buffer get the specified expectedRemaining room from the current position. This method works even if you didn't set autoExpand to true. -
expand
Changes the capacity and limit of this buffer so this buffer get the specified expectedRemaining room from the specified pos. This method works even if you didn't set autoExpand to true. -
isPooled
public abstract boolean isPooled()Returns true if and only if this buffer is returned back to the buffer pool when released.The default value of this property is true if and only if you allocated this buffer using
allocate(int)
orallocate(int, boolean)
, or false otherwise. (i.e.wrap(byte[])
,wrap(byte[], int, int)
, andwrap(java.nio.ByteBuffer)
) -
setPooled
public abstract void setPooled(boolean pooled) Sets whether this buffer is returned back to the buffer pool when released.The default value of this property is true if and only if you allocated this buffer using
allocate(int)
orallocate(int, boolean)
, or false otherwise. (i.e.wrap(byte[])
,wrap(byte[], int, int)
, andwrap(java.nio.ByteBuffer)
) -
position
public abstract int position()- See Also:
-
position
- See Also:
-
limit
public abstract int limit()- See Also:
-
limit
- See Also:
-
mark
- See Also:
-
markValue
public abstract int markValue()Returns the position of the current mark. This method returns -1 if no mark is set. -
reset
- See Also:
-
clear
- See Also:
-
sweep
Clears this buffer and fills its content with NUL. The position is set to zero, the limit is set to the capacity, and the mark is discarded. -
sweep
Clears this buffer and fills its content with value. The position is set to zero, the limit is set to the capacity, and the mark is discarded. -
flip
- See Also:
-
rewind
- See Also:
-
remaining
public int remaining()- See Also:
-
hasRemaining
public boolean hasRemaining()- See Also:
-
duplicate
- See Also:
-
slice
- See Also:
-
asReadOnlyBuffer
- See Also:
-
array
public abstract byte[] array()- See Also:
-
arrayOffset
public abstract int arrayOffset()- See Also:
-
get
public abstract byte get()- See Also:
-
getUnsigned
public short getUnsigned()Reads one unsigned byte as a short integer. -
put
- See Also:
-
get
public abstract byte get(int index) - See Also:
-
getUnsigned
public short getUnsigned(int index) Reads one byte as an unsigned short integer. -
put
- See Also:
-
get
- See Also:
-
get
- See Also:
-
put
Writes the content of the specified src into this buffer. -
put
Writes the content of the specified src into this buffer. -
put
- See Also:
-
put
- See Also:
-
compact
- See Also:
-
toString
-
hashCode
public int hashCode() -
equals
-
compareTo
- Specified by:
compareTo
in interfaceComparable<ByteBuffer>
-
order
- See Also:
-
order
- See Also:
-
getChar
public abstract char getChar()- See Also:
-
putChar
- See Also:
-
getChar
public abstract char getChar(int index) - See Also:
-
putChar
- See Also:
-
asCharBuffer
- See Also:
-
getShort
public abstract short getShort()- See Also:
-
getUnsignedShort
public int getUnsignedShort()Reads two bytes unsigned integer. -
putShort
- See Also:
-
getShort
public abstract short getShort(int index) - See Also:
-
getUnsignedShort
public int getUnsignedShort(int index) Reads two bytes unsigned integer. -
putShort
- See Also:
-
asShortBuffer
- See Also:
-
getInt
public abstract int getInt()- See Also:
-
getUnsignedInt
public long getUnsignedInt()Reads four bytes unsigned integer. -
putInt
- See Also:
-
getInt
public abstract int getInt(int index) - See Also:
-
getUnsignedInt
public long getUnsignedInt(int index) Reads four bytes unsigned integer. -
putInt
- See Also:
-
asIntBuffer
- See Also:
-
getLong
public abstract long getLong()- See Also:
-
putLong
- See Also:
-
getLong
public abstract long getLong(int index) - See Also:
-
putLong
- See Also:
-
asLongBuffer
- See Also:
-
getFloat
public abstract float getFloat()- See Also:
-
putFloat
- See Also:
-
getFloat
public abstract float getFloat(int index) - See Also:
-
putFloat
- See Also:
-
asFloatBuffer
- See Also:
-
getDouble
public abstract double getDouble()- See Also:
-
putDouble
- See Also:
-
getDouble
public abstract double getDouble(int index) - See Also:
-
putDouble
- See Also:
-
asDoubleBuffer
- See Also:
-
asInputStream
Returns anInputStream
that reads the data from this buffer.InputStream.read()
returns -1 if the buffer position reaches to the limit. -
asOutputStream
Returns anOutputStream
that appends the data into this buffer. Please note that theOutputStream.write(int)
will throw aBufferOverflowException
instead of anIOException
in case of buffer overflow. Please set autoExpand property by callingsetAutoExpand(boolean)
to prevent the unexpected runtime exception. -
getHexDump
Returns hexdump of this buffer. -
getString
Reads aNUL
-terminated string from this buffer using the specifieddecoder
and returns it. This method reads until the limit of this buffer if no NUL is found.- Throws:
CharacterCodingException
-
getString
Reads aNUL
-terminated string from this buffer using the specifieddecoder
and returns it.- Parameters:
fieldSize
- the maximum number of bytes to read- Throws:
CharacterCodingException
-
putString
public ByteBuffer putString(CharSequence val, CharsetEncoder encoder) throws CharacterCodingException Writes the content ofin
into this buffer using the specifiedencoder
. This method doesn't terminate string with NUL. You have to do it by yourself.- Throws:
BufferOverflowException
- if the specified string doesn't fitCharacterCodingException
-
putString
public ByteBuffer putString(CharSequence val, int fieldSize, CharsetEncoder encoder) throws CharacterCodingException Writes the content ofin
into this buffer as aNUL
-terminated string using the specifiedencoder
.If the charset name of the encoder is UTF-16, you cannot specify odd
fieldSize
, and this method will append twoNUL
s as a terminator.Please note that this method doesn't terminate with
NUL
if the input string is longer than fieldSize.- Parameters:
fieldSize
- the maximum number of bytes to write- Throws:
CharacterCodingException
-
getPrefixedString
Reads a string which has a 16-bit length field before the actual encoded string, using the specifieddecoder
and returns it. This method is a shortcut for getPrefixedString(2, decoder).- Throws:
CharacterCodingException
-
getPrefixedString
public String getPrefixedString(int prefixLength, CharsetDecoder decoder) throws CharacterCodingException Reads a string which has a length field before the actual encoded string, using the specifieddecoder
and returns it.- Parameters:
prefixLength
- the length of the length field (1, 2, or 4)- Throws:
CharacterCodingException
-
putPrefixedString
public ByteBuffer putPrefixedString(CharSequence in, CharsetEncoder encoder) throws CharacterCodingException Writes the content ofin
into this buffer as a string which has a 16-bit length field before the actual encoded string, using the specifiedencoder
. This method is a shortcut for putPrefixedString(in, 2, 0, encoder).- Throws:
BufferOverflowException
- if the specified string doesn't fitCharacterCodingException
-
putPrefixedString
public ByteBuffer putPrefixedString(CharSequence in, int prefixLength, CharsetEncoder encoder) throws CharacterCodingException Writes the content ofin
into this buffer as a string which has a 16-bit length field before the actual encoded string, using the specifiedencoder
. This method is a shortcut for putPrefixedString(in, prefixLength, 0, encoder).- Parameters:
prefixLength
- the length of the length field (1, 2, or 4)- Throws:
BufferOverflowException
- if the specified string doesn't fitCharacterCodingException
-
putPrefixedString
public ByteBuffer putPrefixedString(CharSequence in, int prefixLength, int padding, CharsetEncoder encoder) throws CharacterCodingException Writes the content ofin
into this buffer as a string which has a 16-bit length field before the actual encoded string, using the specifiedencoder
. This method is a shortcut for putPrefixedString(in, prefixLength, padding, ( byte ) 0, encoder).- Parameters:
prefixLength
- the length of the length field (1, 2, or 4)padding
- the number of padded NULs (1 (or 0), 2, or 4)- Throws:
BufferOverflowException
- if the specified string doesn't fitCharacterCodingException
-
putPrefixedString
public ByteBuffer putPrefixedString(CharSequence val, int prefixLength, int padding, byte padValue, CharsetEncoder encoder) throws CharacterCodingException Writes the content ofin
into this buffer as a string which has a 16-bit length field before the actual encoded string, using the specifiedencoder
.- Parameters:
prefixLength
- the length of the length field (1, 2, or 4)padding
- the number of padded bytes (1 (or 0), 2, or 4)padValue
- the value of padded bytes- Throws:
BufferOverflowException
- if the specified string doesn't fitCharacterCodingException
-
getObject
Reads a Java object from the buffer using the contextClassLoader
of the current thread.- Throws:
ClassNotFoundException
-
getObject
Reads a Java object from the buffer using the specified classLoader.- Throws:
ClassNotFoundException
-
putObject
Writes the specified Java object to the buffer. -
prefixedDataAvailable
public boolean prefixedDataAvailable(int prefixLength) Returns true if this buffer contains a data which has a data length as a prefix and the buffer has remaining data as enough as specified in the data length field. This method is identical with prefixedDataAvailable( prefixLength, Integer.MAX_VALUE ). Please not that using this method can allow DoS (Denial of Service) attack in case the remote peer sends too big data length value. It is recommended to useprefixedDataAvailable(int, int)
instead.- Parameters:
prefixLength
- the length of the prefix field (1, 2, or 4)- Throws:
IllegalArgumentException
- if prefixLength is wrongBufferDataException
- if data length is negative
-
prefixedDataAvailable
public boolean prefixedDataAvailable(int prefixLength, int maxDataLength) Returns true if this buffer contains a data which has a data length as a prefix and the buffer has remaining data as enough as specified in the data length field.- Parameters:
prefixLength
- the length of the prefix field (1, 2, or 4)maxDataLength
- the allowed maximum of the read data length- Throws:
IllegalArgumentException
- if prefixLength is wrongBufferDataException
- if data length is negative or greater then maxDataLength
-
skip
Forwards the position of this buffer as the specifiedsize
bytes. -
fill
Fills this buffer with the specified value. This method moves buffer position forward. -
fillAndReset
Fills this buffer with the specified value. This method does not change buffer position. -
fill
Fills this buffer withNUL (0x00)
. This method moves buffer position forward. -
fillAndReset
Fills this buffer withNUL (0x00)
. This method does not change buffer position. -
autoExpand
This method forwards the call toexpand(int)
only when autoExpand property is true. -
autoExpand
This method forwards the call toexpand(int)
only when autoExpand property is true.
-