1 16 package org.mortbay.util; 17 18 19 20 26 public class ByteArrayPool 27 { 28 public static final int __POOL_SIZE= 29 Integer.getInteger("org.mortbay.util.ByteArrayPool.pool_size",8).intValue(); 30 31 public static final ThreadLocal __pools=new BAThreadLocal(); 32 public static int __slot; 33 34 35 39 public static byte[] getByteArray(int size) 40 { 41 byte[][] pool = (byte[][])__pools.get(); 42 boolean full=true; 43 for (int i=pool.length;i-->0;) 44 { 45 if (pool[i]!=null && pool[i].length==size) 46 { 47 byte[]b = pool[i]; 48 pool[i]=null; 49 return b; 50 } 51 else 52 full=false; 53 } 54 55 if (full) 56 for (int i=pool.length;i-->0;) 57 pool[i]=null; 58 59 return new byte[size]; 60 } 61 62 63 public static byte[] getByteArrayAtLeast(int minSize) 64 { 65 byte[][] pool = (byte[][])__pools.get(); 66 for (int i=pool.length;i-->0;) 67 { 68 if (pool[i]!=null && pool[i].length>=minSize) 69 { 70 byte[]b = pool[i]; 71 pool[i]=null; 72 return b; 73 } 74 } 75 76 return new byte[minSize]; 77 } 78 79 80 81 public static void returnByteArray(final byte[] b) 82 { 83 if (b==null) 84 return; 85 86 byte[][] pool = (byte[][])__pools.get(); 87 for (int i=pool.length;i-->0;) 88 { 89 if (pool[i]==null) 90 { 91 pool[i]=b; 92 return; 93 } 94 } 95 96 int s = __slot++; 98 if (s<0)s=-s; 99 pool[s%pool.length]=b; 100 } 101 102 103 104 105 private static final class BAThreadLocal extends ThreadLocal 106 { 107 protected Object initialValue() 108 { 109 return new byte[__POOL_SIZE][]; 110 } 111 } 112 } 113 | Popular Tags |