1 package com.bumptech.glide.util; 2 3 import android.util.Log; 4 5 import java.util.Queue; 6 7 /** 8 * A pool for reusing byte arrays that produces and contains byte arrays of a fixed size. 9 */ 10 public final class ByteArrayPool { 11 private static final String TAG = "ByteArrayPool"; 12 // 64 KB. 13 private static final int TEMP_BYTES_SIZE = 64 * 1024; 14 // 512 KB. 15 private static final int MAX_SIZE = 2 * 1048 * 1024; 16 private static final int MAX_BYTE_ARRAY_COUNT = MAX_SIZE / TEMP_BYTES_SIZE; 17 18 private final Queue<byte[]> tempQueue = Util.createQueue(0); 19 private static final ByteArrayPool BYTE_ARRAY_POOL = new ByteArrayPool(); 20 21 /** 22 * Returns a constant singleton byte array pool. 23 */ 24 public static ByteArrayPool get() { 25 return BYTE_ARRAY_POOL; 26 } 27 28 private ByteArrayPool() { } 29 30 /** 31 * Removes all byte arrays from the pool. 32 */ 33 public void clear() { 34 synchronized (tempQueue) { 35 tempQueue.clear(); 36 } 37 } 38 39 /** 40 * Returns a byte array by retrieving one from the pool if the pool is non empty or otherwise by creating a new 41 * byte array. 42 */ 43 public byte[] getBytes() { 44 byte[] result; 45 synchronized (tempQueue) { 46 result = tempQueue.poll(); 47 } 48 if (result == null) { 49 result = new byte[TEMP_BYTES_SIZE]; 50 if (Log.isLoggable(TAG, Log.DEBUG)) { 51 Log.d(TAG, "Created temp bytes"); 52 } 53 } 54 return result; 55 } 56 57 /** 58 * Adds the given byte array to the pool if it is the correct size and the pool is not full and returns true if 59 * the byte array was added and false otherwise. 60 * 61 * @param bytes The bytes to try to add to the pool. 62 */ 63 public boolean releaseBytes(byte[] bytes) { 64 if (bytes.length != TEMP_BYTES_SIZE) { 65 return false; 66 } 67 68 boolean accepted = false; 69 synchronized (tempQueue) { 70 if (tempQueue.size() < MAX_BYTE_ARRAY_COUNT) { 71 accepted = true; 72 tempQueue.offer(bytes); 73 } 74 } 75 return accepted; 76 } 77 } 78