| 1 | /* |
| 2 | * Copyright (c) 2013, 2021 Oracle and/or its affiliates. All rights reserved. |
| 3 | * |
| 4 | * This program and the accompanying materials are made available under the |
| 5 | * terms of the Eclipse Public License v. 2.0, which is available at |
| 6 | * http://www.eclipse.org/legal/epl-2.0. |
| 7 | * |
| 8 | * This Source Code may also be made available under the following Secondary |
| 9 | * Licenses when the conditions for such availability set forth in the |
| 10 | * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, |
| 11 | * version 2 with the GNU Classpath Exception, which is available at |
| 12 | * https://www.gnu.org/software/classpath/license.html. |
| 13 | * |
| 14 | * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 |
| 15 | */ |
| 16 | |
| 17 | package org.eclipse.parsson; |
| 18 | |
| 19 | import org.eclipse.parsson.api.BufferPool; |
| 20 | |
| 21 | import java.lang.ref.WeakReference; |
| 22 | import java.util.concurrent.ConcurrentLinkedQueue; |
| 23 | |
| 24 | /** |
| 25 | * char[] pool that pool instances of char[] which are expensive to create. |
| 26 | * |
| 27 | * @author Jitendra Kotamraju |
| 28 | */ |
| 29 | class BufferPoolImpl implements BufferPool { |
| 30 | |
| 31 | // volatile since multiple threads may access queue reference |
| 32 | private volatile WeakReference<ConcurrentLinkedQueue<char[]>> queue; |
| 33 | |
| 34 | /** |
| 35 | * Gets a new object from the pool. |
| 36 | * |
| 37 | * <p> |
| 38 | * If no object is available in the pool, this method creates a new one. |
| 39 | * |
| 40 | * @return |
| 41 | * always non-null. |
| 42 | */ |
| 43 | @Override |
| 44 | public final char[] take() { |
| 45 | char[] t = getQueue().poll(); |
| 46 | if (t==null) |
| 47 | return new char[4096]; |
| 48 | return t; |
| 49 | } |
| 50 | |
| 51 | private ConcurrentLinkedQueue<char[]> getQueue() { |
| 52 | WeakReference<ConcurrentLinkedQueue<char[]>> q = queue; |
| 53 | if (q != null) { |
| 54 | ConcurrentLinkedQueue<char[]> d = q.get(); |
| 55 | if (d != null) |
| 56 | return d; |
| 57 | } |
| 58 | |
| 59 | // overwrite the queue |
| 60 | ConcurrentLinkedQueue<char[]> d = new ConcurrentLinkedQueue<>(); |
| 61 | queue = new WeakReference<>(d); |
| 62 | |
| 63 | return d; |
| 64 | } |
| 65 | |
| 66 | /** |
| 67 | * Returns an object back to the pool. |
| 68 | */ |
| 69 | @Override |
| 70 | public final void recycle(char[] t) { |
| 71 | getQueue().offer(t); |
| 72 | } |
| 73 | |
| 74 | } |