All Downloads are FREE. Search and download functionalities are using the official Maven repository.

co.elastic.otel.profiler.pooling.AbstractObjectPool Maven / Gradle / Ivy

The newest version!
/*
 * Licensed to Elasticsearch B.V. under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch B.V. licenses this file to you under
 * the Apache License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package co.elastic.otel.profiler.pooling;

import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;

public abstract class AbstractObjectPool implements ObjectPool {

  protected final Allocator allocator;
  protected final Resetter resetter;
  private final AtomicInteger garbageCreated;

  protected AbstractObjectPool(Allocator allocator, Resetter resetter) {
    this.allocator = allocator;
    this.resetter = resetter;
    this.garbageCreated = new AtomicInteger();
  }

  @Override
  public final T createInstance() {
    T object = tryCreateInstance();
    if (object == null) {
      // pool does not have available instance, falling back to creating a new one
      object = allocator.createInstance();
    }
    return object;
  }

  @Override
  public final void recycle(T obj) {
    resetter.recycle(obj);
    if (!returnToPool(obj)) {
      // when not able to return object to pool, it means this object will be garbage-collected
      garbageCreated.incrementAndGet();
    }
  }

  public final long getGarbageCreated() {
    return garbageCreated.longValue();
  }

  /**
   * Pushes object reference back into the available pooled instances
   *
   * @param obj recycled object to return to pool
   * @return true if object has been returned to pool, false if pool is already full
   */
  protected abstract boolean returnToPool(T obj);

  /**
   * Tries to create an instance in pool
   *
   * @return {@code null} if pool capacity is exhausted
   */
  @Nullable
  protected abstract T tryCreateInstance();
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy