1 22 package org.xsocket.stream.io.impl; 23 24 25 import java.nio.ByteBuffer ; 26 import java.util.logging.Level ; 27 import java.util.logging.Logger ; 28 29 30 31 37 final class UnsynchronizedMemoryManager implements IMemoryManager { 38 39 private static final Logger LOG = Logger.getLogger(UnsynchronizedMemoryManager.class.getName()); 40 41 private ByteBuffer freeBuffer = null; 42 43 private boolean useDirectMemory = false; 44 private int preallocationSize = 65536; 45 46 47 53 UnsynchronizedMemoryManager(int preallocationSize, boolean useDirectMemory) { 54 this.preallocationSize = preallocationSize; 55 this.useDirectMemory = useDirectMemory; 56 } 57 58 61 public int getCurrentPreallocationBufferSize() { 62 ByteBuffer b = freeBuffer; 63 if (b == null) { 64 return 0; 65 } else { 66 return b.remaining(); 67 } 68 } 69 70 71 74 public void recycleMemory(ByteBuffer buffer, int minSize) { 75 int remaining = buffer.remaining(); 76 if (remaining >= minSize) { 77 freeBuffer = buffer; 78 } 79 } 80 81 82 85 public final ByteBuffer acquireMemory(int minSize) { 86 preallocate(minSize); 87 88 ByteBuffer buffer = freeBuffer; 89 freeBuffer = null; 90 91 return buffer; 92 } 93 94 95 98 public void preallocate(int minSize) { 99 100 if (freeBuffer != null) { 102 if (freeBuffer.remaining() >= minSize) { 103 return; 104 } 105 } 106 107 freeBuffer = newBuffer(preallocationSize); 109 } 110 111 112 115 private ByteBuffer newBuffer(int preallocationSize) { 116 if (LOG.isLoggable(Level.FINE)) { 117 LOG.fine("allocate new physical memory (size: " + preallocationSize + ") by thread " + Thread.currentThread().getName()); 118 } 119 120 if (useDirectMemory) { 121 return ByteBuffer.allocateDirect(preallocationSize); 122 } else { 123 return ByteBuffer.allocate(preallocationSize); 124 } 125 } 126 127 130 public int getFreeBufferSize() { 131 if (freeBuffer != null) { 132 return freeBuffer.remaining(); 133 } else { 134 return 0; 135 } 136 } 137 } 138 | Popular Tags |