对象池技术

package com.iluwatar.object.pool;

/**
 * Oliphaunt object pool.
 */
public class OliphauntPool extends ObjectPool<Oliphaunt> {

  @Override
  protected Oliphaunt create() {
    return new Oliphaunt();
  }
}

package com.iluwatar.object.pool;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Oliphaunts are expensive to create.
 */
public class Oliphaunt {

  private static final AtomicInteger counter = new AtomicInteger(0);

  private final int id;

  /**
   * Constructor.
   */
  public Oliphaunt() {
    id = counter.incrementAndGet();
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  public int getId() {
    return id;
  }

  @Override
  public String toString() {
    return String.format("Oliphaunt id=%d", id);
  }
}
package com.iluwatar.object.pool;

import java.util.HashSet;
import java.util.Set;

/**
 * Generic object pool.
 *
 * @param <T> Type T of Object in the Pool
 */
public abstract class ObjectPool<T> {

  private final Set<T> available = new HashSet<>();
  private final Set<T> inUse = new HashSet<>();

  protected abstract T create();

  /**
   * Checkout object from pool.
   */
  public synchronized T checkOut() {
    if (available.isEmpty()) {
      available.add(create());
    }
    var instance = available.iterator().next();
    available.remove(instance);
    inUse.add(instance);
    return instance;
  }

  public synchronized void checkIn(T instance) {
    inUse.remove(instance);
    available.add(instance);
  }

  @Override
  public synchronized String toString() {
    return String.format("Pool available=%d inUse=%d", available.size(), inUse.size());
  }
}
package com.iluwatar.object.pool;

import lombok.extern.slf4j.Slf4j;

/**
 * When it is necessary to work with a large number of objects that are particularly expensive to
 * instantiate and each object is only needed for a short period of time, the performance of an
 * entire application may be adversely affected. An object pool design pattern may be deemed
 * desirable in cases such as these.
 *
 * <p>The object pool design pattern creates a set of objects that may be reused. When a new object
 * is needed, it is requested from the pool. If a previously prepared object is available it is
 * returned immediately, avoiding the instantiation cost. If no objects are present in the pool, a
 * new item is created and returned. When the object has been used and is no longer needed, it is
 * returned to the pool, allowing it to be used again in the future without repeating the
 * computationally expensive instantiation process. It is important to note that once an object has
 * been used and returned, existing references will become invalid.
 *
 * <p>In this example we have created {@link OliphauntPool} inheriting from generic {@link
 * ObjectPool}. {@link Oliphaunt}s can be checked out from the pool and later returned to it. The
 * pool tracks created instances and their status (available, inUse).
 */
@Slf4j
public class App {

  /**
   * Program entry point.
   *
   * @param args command line args
   */
  public static void main(String[] args) {
    var pool = new OliphauntPool();
    LOGGER.info(pool.toString());
    var oliphaunt1 = pool.checkOut();
    String checkedOut = "Checked out {}";

    LOGGER.info(checkedOut, oliphaunt1);
    LOGGER.info(pool.toString());
    var oliphaunt2 = pool.checkOut();
    LOGGER.info(checkedOut, oliphaunt2);
    var oliphaunt3 = pool.checkOut();
    LOGGER.info(checkedOut, oliphaunt3);
    LOGGER.info(pool.toString());
    LOGGER.info("Checking in {}", oliphaunt1);
    pool.checkIn(oliphaunt1);
    LOGGER.info("Checking in {}", oliphaunt2);
    pool.checkIn(oliphaunt2);
    LOGGER.info(pool.toString());
    var oliphaunt4 = pool.checkOut();
    LOGGER.info(checkedOut, oliphaunt4);
    var oliphaunt5 = pool.checkOut();
    LOGGER.info(checkedOut, oliphaunt5);
    LOGGER.info(pool.toString());
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值