ByteArrayPool.java revision fe090f50f3040f4d478143a3e0ffa8cdf813fefc
1package com.bumptech.glide.util;
2
3import android.util.Log;
4
5import java.util.ArrayDeque;
6import java.util.Queue;
7
8public final class ByteArrayPool {
9    private static final String TAG = "ByteArrayPool";
10    // 64 KB.
11    private static final int TEMP_BYTES_SIZE = 64 * 1024;
12    // 512 KB.
13    private static final int MAX_SIZE = 2 * 1048 * 1024;
14    private static final int MAX_BYTE_ARRAY_COUNT = MAX_SIZE / TEMP_BYTES_SIZE;
15
16    private final Queue<byte[]> tempQueue = new ArrayDeque<byte[]>();
17    private static final ByteArrayPool BYTE_ARRAY_POOL = new ByteArrayPool();
18
19    public static ByteArrayPool get() {
20        return BYTE_ARRAY_POOL;
21    }
22
23    private ByteArrayPool() {  }
24
25    public void clear() {
26        synchronized (tempQueue) {
27            tempQueue.clear();
28        }
29    }
30
31    public byte[] getBytes() {
32        byte[] result;
33        synchronized (tempQueue) {
34            result = tempQueue.poll();
35        }
36        if (result == null) {
37            result = new byte[TEMP_BYTES_SIZE];
38            if (Log.isLoggable(TAG, Log.DEBUG)) {
39                Log.d(TAG, "Created temp bytes");
40            }
41        }
42        return result;
43    }
44
45    public boolean releaseBytes(byte[] bytes) {
46        if (bytes.length != TEMP_BYTES_SIZE) {
47            return false;
48        }
49
50        boolean accepted = false;
51        synchronized (tempQueue) {
52            if (tempQueue.size() < MAX_BYTE_ARRAY_COUNT) {
53                accepted = true;
54                tempQueue.offer(bytes);
55            }
56        }
57        return accepted;
58    }
59}
60