1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.tv.settings.util;
18 
19 import java.util.ArrayList;
20 import java.util.List;
21 
22 public final class ByteArrayPool {
23 
24     public static final int CHUNK16K = 16 * 1024;
25     public static final int DEFAULT_MAX_NUM = 8;
26 
27     private final static ByteArrayPool sChunk16K = new ByteArrayPool(CHUNK16K, DEFAULT_MAX_NUM);
28 
29     private final ArrayList<byte[]> mCachedBuf;
30     private final int mChunkSize;
31     private final int mMaxNum;
32 
ByteArrayPool(int chunkSize, int maxNum)33     private ByteArrayPool(int chunkSize, int maxNum) {
34         mChunkSize = chunkSize;
35         mMaxNum = maxNum;
36         mCachedBuf = new ArrayList<byte[]>(mMaxNum);
37     }
38 
39     /**
40      * get singleton of 16KB byte[] pool
41      */
get16KBPool()42     public static ByteArrayPool get16KBPool() {
43         return sChunk16K;
44     }
45 
allocateChunk()46     public byte[] allocateChunk() {
47         synchronized (mCachedBuf) {
48             int size = mCachedBuf.size();
49             if (size > 0) {
50                 return mCachedBuf.remove(size - 1);
51             }
52             return new byte[mChunkSize];
53         }
54     }
55 
clear()56     public void clear() {
57         synchronized (mCachedBuf) {
58             mCachedBuf.clear();
59         }
60     }
61 
releaseChunk(byte[] buf)62     public void releaseChunk(byte[] buf) {
63         if (buf == null || buf.length != mChunkSize) {
64             return;
65         }
66         synchronized (mCachedBuf) {
67             if (mCachedBuf.size() < mMaxNum) {
68                 mCachedBuf.add(buf);
69             }
70         }
71     }
72 
releaseChunks(List<byte[]> bufs)73     public void releaseChunks(List<byte[]> bufs) {
74         synchronized (mCachedBuf) {
75             for (int i = 0, c = bufs.size(); i < c; i++) {
76                 if (mCachedBuf.size() == mMaxNum) {
77                     break;
78                 }
79                 byte[] buf = bufs.get(i);
80                 if (buf != null && buf.length == mChunkSize) {
81                     mCachedBuf.add(bufs.get(i));
82                 }
83             }
84         }
85     }
86 
87 }
88