1/* 2 * Copyright (C) 2014 Square, Inc. 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 */ 16package okio; 17 18/** 19 * A collection of unused segments, necessary to avoid GC churn and zero-fill. 20 * This pool is a thread-safe static singleton. 21 */ 22final class SegmentPool { 23 static final SegmentPool INSTANCE = new SegmentPool(); 24 25 /** The maximum number of bytes to pool. */ 26 // TODO: Is 64 KiB a good maximum size? Do we ever have that many idle segments? 27 static final long MAX_SIZE = 64 * 1024; // 64 KiB. 28 29 /** Singly-linked list of segments. */ 30 private Segment next; 31 32 /** Total bytes in this pool. */ 33 long byteCount; 34 35 private SegmentPool() { 36 } 37 38 Segment take() { 39 synchronized (this) { 40 if (next != null) { 41 Segment result = next; 42 next = result.next; 43 result.next = null; 44 byteCount -= Segment.SIZE; 45 return result; 46 } 47 } 48 return new Segment(); // Pool is empty. Don't zero-fill while holding a lock. 49 } 50 51 void recycle(Segment segment) { 52 if (segment.next != null || segment.prev != null) throw new IllegalArgumentException(); 53 synchronized (this) { 54 if (byteCount + Segment.SIZE > MAX_SIZE) return; // Pool is full. 55 byteCount += Segment.SIZE; 56 segment.next = next; 57 segment.pos = segment.limit = 0; 58 next = segment; 59 } 60 } 61} 62