InflaterCache.java

  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. package org.eclipse.jgit.lib;

  12. import java.util.zip.Inflater;

  13. /**
  14.  * Creates zlib based inflaters as necessary for object decompression.
  15.  */
  16. public class InflaterCache {
  17.     private static final int SZ = 4;

  18.     private static final Inflater[] inflaterCache;

  19.     private static int openInflaterCount;

  20.     static {
  21.         inflaterCache = new Inflater[SZ];
  22.     }

  23.     /**
  24.      * Obtain an Inflater for decompression.
  25.      * <p>
  26.      * Inflaters obtained through this cache should be returned (if possible) by
  27.      * {@link #release(Inflater)} to avoid garbage collection and reallocation.
  28.      *
  29.      * @return an available inflater. Never null.
  30.      */
  31.     public static Inflater get() {
  32.         final Inflater r = getImpl();
  33.         return r != null ? r : new Inflater(false);
  34.     }

  35.     private static synchronized Inflater getImpl() {
  36.         if (openInflaterCount > 0) {
  37.             final Inflater r = inflaterCache[--openInflaterCount];
  38.             inflaterCache[openInflaterCount] = null;
  39.             return r;
  40.         }
  41.         return null;
  42.     }

  43.     /**
  44.      * Release an inflater previously obtained from this cache.
  45.      *
  46.      * @param i
  47.      *            the inflater to return. May be null, in which case this method
  48.      *            does nothing.
  49.      */
  50.     public static void release(Inflater i) {
  51.         if (i != null) {
  52.             i.reset();
  53.             if (releaseImpl(i))
  54.                 i.end();
  55.         }
  56.     }

  57.     private static synchronized boolean releaseImpl(Inflater i) {
  58.         if (openInflaterCount < SZ) {
  59.             inflaterCache[openInflaterCount++] = i;
  60.             return false;
  61.         }
  62.         return true;
  63.     }

  64.     private InflaterCache() {
  65.         throw new UnsupportedOperationException();
  66.     }
  67. }