View Javadoc
1   /*
2    * Copyright (C) 2008, Google Inc.
3    * Copyright (C) 2006-2008, Shawn O. Pearce <spearce@spearce.org> and others
4    *
5    * This program and the accompanying materials are made available under the
6    * terms of the Eclipse Distribution License v. 1.0 which is available at
7    * https://www.eclipse.org/org/documents/edl-v10.php.
8    *
9    * SPDX-License-Identifier: BSD-3-Clause
10   */
11  
12  package org.eclipse.jgit.lib;
13  
14  import java.util.zip.Inflater;
15  
16  /**
17   * Creates zlib based inflaters as necessary for object decompression.
18   */
19  public class InflaterCache {
20  	private static final int SZ = 4;
21  
22  	private static final Inflater[] inflaterCache;
23  
24  	private static int openInflaterCount;
25  
26  	static {
27  		inflaterCache = new Inflater[SZ];
28  	}
29  
30  	/**
31  	 * Obtain an Inflater for decompression.
32  	 * <p>
33  	 * Inflaters obtained through this cache should be returned (if possible) by
34  	 * {@link #release(Inflater)} to avoid garbage collection and reallocation.
35  	 *
36  	 * @return an available inflater. Never null.
37  	 */
38  	public static Inflater get() {
39  		final Inflater r = getImpl();
40  		return r != null ? r : new Inflater(false);
41  	}
42  
43  	private static synchronized Inflater getImpl() {
44  		if (openInflaterCount > 0) {
45  			final Inflater r = inflaterCache[--openInflaterCount];
46  			inflaterCache[openInflaterCount] = null;
47  			return r;
48  		}
49  		return null;
50  	}
51  
52  	/**
53  	 * Release an inflater previously obtained from this cache.
54  	 *
55  	 * @param i
56  	 *            the inflater to return. May be null, in which case this method
57  	 *            does nothing.
58  	 */
59  	public static void release(Inflater i) {
60  		if (i != null) {
61  			i.reset();
62  			if (releaseImpl(i))
63  				i.end();
64  		}
65  	}
66  
67  	private static synchronized boolean releaseImpl(Inflater i) {
68  		if (openInflaterCount < SZ) {
69  			inflaterCache[openInflaterCount++] = i;
70  			return false;
71  		}
72  		return true;
73  	}
74  
75  	private InflaterCache() {
76  		throw new UnsupportedOperationException();
77  	}
78  }