@@ -24,22 +24,21 @@ public class Buffer {
2424
2525 static {
2626 try {
27- // http://github.com/airlift/slice
28-
29- // fetch theUnsafe object
27+ // Fetch theUnsafe object for Orackle JDK and OpenJDK
3028 Field field = Unsafe .class .getDeclaredField ("theUnsafe" );
3129 field .setAccessible (true );
3230 unsafe = (Unsafe ) field .get (null );
3331 if (unsafe == null ) {
34- throw new RuntimeException ("Unsafe access not available " );
32+ throw new RuntimeException ("Unsafe is unavailable " );
3533 }
34+ // TODO Finding Unsafe instance for Android JVM
3635
37- // make sure the VM thinks bytes are only one byte wide
36+ // Make sure the VM thinks bytes are only one byte wide
3837 if (sun .misc .Unsafe .ARRAY_BYTE_INDEX_SCALE != 1 ) {
3938 throw new IllegalStateException ("Byte array index scale must be 1, but is " + ARRAY_BYTE_INDEX_SCALE );
4039 }
4140
42- // fetch a method handle for the hidden constructor for DirectByteBuffer
41+ // Fetch a method handle for the hidden constructor for DirectByteBuffer
4342 Class <?> directByteBufferClass = ClassLoader .getSystemClassLoader ().loadClass ("java.nio.DirectByteBuffer" );
4443 Constructor <?> constructor = directByteBufferClass .getDeclaredConstructor (long .class , int .class , Object .class );
4544 constructor .setAccessible (true );
@@ -76,9 +75,35 @@ public class Buffer {
7675
7776 private AtomicInteger referenceCounter ;
7877
79- static {
80- // something depending on architecture to get unsafe
81- //@Suppress...
78+
79+ static Buffer newOffHeapBuffer (int length ) {
80+ long address = unsafe .allocateMemory (length );
81+ return new Buffer (address , length );
82+ }
83+
84+ public static Buffer newDirectBuffer (int length ) {
85+ return new Buffer (ByteBuffer .allocateDirect (length ));
86+ }
87+
88+ public static Buffer newBuffer (int length ) {
89+ return new Buffer (ByteBuffer .allocate (length ));
90+ }
91+
92+ public static void releaseBuffer (Buffer buffer ) {
93+ if (buffer .base instanceof byte []) {
94+ // We have nothing to do. Wait until the garbage-collector collects this array object
95+ }
96+ else {
97+ unsafe .freeMemory (buffer .address );
98+ }
99+ }
100+
101+
102+ Buffer (long address , int length ) {
103+ this .base = null ;
104+ this .address = address ;
105+ this .size = length ;
106+ this .reference = null ;
82107 }
83108
84109 public Buffer (ByteBuffer bb ) {
@@ -107,6 +132,8 @@ public Buffer(byte[] arr) {
107132 this .reference = null ;
108133 }
109134
135+ public int size () { return size ; }
136+
110137
111138 public byte getByte (int index ) {
112139 return unsafe .getByte (base , address + index );
0 commit comments