简易对象池

Posted --zz

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了简易对象池相关的知识,希望对你有一定的参考价值。

简易的对象池,需要深入了解的话,得阅读<<Thinking in Pattern>>

import java.util.*;
import java.util.concurrent.*;

/**
 * 对象池
 * @author Administrator
 *
 * @param <T>
 */
class Pool<T>{
	private int size;
	private List<T> items = new ArrayList<T>();
	private volatile boolean[] isCheckedOut;
	Semaphore signalControl;
	public Pool(int size,Class<T> classObject) {
		signalControl = new Semaphore(size,true);
		this.size = size;
		isCheckedOut = new boolean[size];
		for(int i=0;i<size;i++) {
			try {
				items.add(classObject.getDeclaredConstructor().newInstance());
			}catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	public void checkIn(T x) {
		if(releaseItem(x)) {
			signalControl.release();
		}
	}
	public T checkOut() throws InterruptedException {
		signalControl.acquire();
		return getItem();		
	}
	public synchronized T getItem() {
		for(int i=0;i<size;i++) {
			if(!isCheckedOut[i]) {
				isCheckedOut[i] = true;
				return items.get(i);
			}
		}
		return null;
	}
	public synchronized boolean releaseItem(T item) {
		int index = items.indexOf(item);
		if(index == -1)
			return false;
		if(isCheckedOut[index]) {
			isCheckedOut[index] = false;
			return true;
		}
		return false;
	}
}

class Fat{
	private volatile double d;
	private static int counter = 0;
	private final int id = counter++;
	public Fat() {
		//构建花费昂贵
		for(int i=1;i<10000;i++) {
			d += (Math.PI + Math.E);
		}
	}
	public void operation() {
		System.out.println(this);
	}
	public String toString() {
		return "Fat id: " + id;
	}
}

class CheckoutTask<T> implements Runnable{
	private static int counter = 0;
	private final int id = counter++;
	private Pool<T> pool;
	public CheckoutTask(Pool<T> pool) {
		this.pool = pool;
	}
	public void run() {
		try {
			T item = pool.checkOut();
			System.out.println("Check out " + item);
			TimeUnit.SECONDS.sleep(1);
			System.out.println("Check in " + item);
			pool.checkIn(item);
		}catch (InterruptedException e) {
			
		}
	}
	public String toString() {
		return "CheckTase " + id + " ";
	}
}

public class Restaurant{
	final static int SIZE = 25;
	public static void main(String[] args) throws Exception {
		//创建一个对象池
		final Pool<Fat> fatPool = new Pool<Fat>(SIZE, Fat.class);
		ExecutorService executorService = Executors.newCachedThreadPool();
		for(int i=0;i<SIZE;i++) {
			executorService.execute(new CheckoutTask<Fat>(fatPool));
		}
		System.out.println("All CheckoutTask created");
		List<Fat> list = new ArrayList<>();
		for(int i=0;i<SIZE;i++) {
			Fat fat = fatPool.checkOut();
			System.out.println(i + ": main() thread check out");
			fat.operation();
			list.add(fat);
		}
		Future<?> blocked = executorService.submit(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					System.out.println("Is leave out?");
					fatPool.checkOut();
				}catch (Exception e) {
					System.out.println("NO");
				}
			}
		});
		
		TimeUnit.SECONDS.sleep(2);
		blocked.cancel(true);
		for(Fat fat:list) {
			fatPool.checkIn(fat);
		}
		for(Fat fat:list) {
			fatPool.checkIn(fat);
		}
		executorService.shutdown();
	}
}

  

以上是关于简易对象池的主要内容,如果未能解决你的问题,请参考以下文章

简易内存池

华为OD机试真题Java实现简易内存池2真题+解题思路+代码(2022&2023)

一个简易内存池(C++)

newCacheThreadPool()newFixedThreadPool()newScheduledThreadPool()newSingleThreadExecutor()自定义线程池(代码片段

连接池报错 Proxool Provider unable to load JAXP configurator file: proxool.xml

使用 LinkedBlockingQueue 实现简易版线程池