对象池模式【其他模式】

对象池模式

package org.zxd.design.pattern.others.objectpool;

import static org.junit.Assert.assertTrue;

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

import org.junit.Test;

import lombok.extern.slf4j.Slf4j;

public class ObjectPool {

    /**
     * 对象池模式:当创建对象和释放对象消耗很大时,可以使用对象池模式实现复用。
     */
    @Test
    public void all() {
        final HeavyPool pool = new HeavyPool();
        final Heavy h1 = pool.checkOut();
        h1.dowork();

        pool.checkIn(h1);
        assertTrue(h1 == pool.checkOut());
    }
}

@Slf4j
class Heavy {
    public Heavy() {
        log.info("initialize for 5 seconds");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> release()));
    }

    public void dowork() {
        log.info("do short work");
    }

    public void release() {
        log.info("do release");
    }
}

class HeavyPool extends Pool<Heavy> {

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

abstract class Pool<T> {
    private final Set<T> available = new HashSet<>();
    private final Set<T> inUse = new HashSet<>();

    protected abstract T create();

    public synchronized T checkOut() {
        if (available.isEmpty()) {
            available.add(create());
        }
        final T 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());
    }
}
原文地址:https://www.cnblogs.com/zhuxudong/p/10171110.html