關(guān)于common pool 對象池的使用

1 繼承工廠類 BasePooledObjectFactory

public class ChannelPoolFactory extends BasePooledObjectFactory<ManagedChannel> {

    private String host;

    private int port;

    private String domain;

    private File cert;

    public ChannelPoolFactory(String host, int port, String domain, String cert) {
        this.host = host;
        this.port = port;
        this.domain = domain;
        URL url = ChannelPoolFactory.class.getClassLoader().getResource(cert);
        this.cert = new File(url.getFile());
    }

    @Override
    public ManagedChannel create() throws SSLException, UnknownHostException {

        SslContext sslContext  = GrpcSslContexts.forClient().trustManager(cert).build();

        InetAddress address = InetAddress.getByAddress(domain, InetAddress.getByName(host).getAddress());

        ManagedChannel channel = NettyChannelBuilder.forAddress(new InetSocketAddress(address, port))
                .negotiationType(NegotiationType.TLS).sslContext(sslContext).build();
        return channel;
    }

2 生成GenericObjectPoolConfig 和 Factory來構(gòu)造 ObjectPool ;

 public GenericObjectPool(PooledObjectFactory<T> factory,
            GenericObjectPoolConfig config) {

        super(config, ONAME_BASE, config.getJmxNamePrefix());

        if (factory == null) {
            jmxUnregister(); // tidy up
            throw new IllegalArgumentException("factory may not be null");
        }
        this.factory = factory;

        idleObjects = new LinkedBlockingDeque<PooledObject<T>>(config.getFairness());

        setConfig(config);

        startEvictor(getTimeBetweenEvictionRunsMillis());
    }

3 在 GenericObjectPool 有borrowObject 和 returnObject方法,以借還池中對象。

在borrowObject中

 p = idleObjects.pollFirst();
                if (p == null) {
                    p = create();
                    if (p != null) {
                        create = true;
                    }
                }
                if (p == null) {
                    if (borrowMaxWaitMillis < 0) {
                        p = idleObjects.takeFirst();
                    } else {
                        p = idleObjects.pollFirst(borrowMaxWaitMillis,
                                TimeUnit.MILLISECONDS);
                    }
                }
                if (p == null) {
                    throw new NoSuchElementException(
                            "Timeout waiting for idle object");
                }
                if (!p.allocate()) {
                    p = null;
                }

在create()中有

  try {
            p = factory.makeObject();
        } catch (Exception e) {
            createCount.decrementAndGet();
            throw e;
        }

在PooledObjectFactory中 makeObject()實現(xiàn)為:

  @Override
    public PooledObject<T> makeObject() throws Exception {
        return wrap(create());
    }

由此可知,如果首次borrowObject,將會調(diào)用工廠方法創(chuàng)建對象。

創(chuàng)建成功后將會執(zhí)行

  updateStatsBorrow(p, System.currentTimeMillis() - waitTime);

        return p.getObject();
final void updateStatsBorrow(PooledObject<T> p, long waitTime) {
        borrowedCount.incrementAndGet();
        idleTimes.add(p.getIdleTimeMillis());
        waitTimes.add(waitTime);

        // lock-free optimistic-locking maximum
        long currentMax;
        do {
            currentMax = maxBorrowWaitTimeMillis.get();
            if (currentMax >= waitTime) {
                break;
            }
        } while (!maxBorrowWaitTimeMillis.compareAndSet(currentMax, waitTime));
    }

此操作將會更新參數(shù)。

4 returnObject

方法用來歸還對象,此處一定要在finally代碼中執(zhí)行。否則每次執(zhí)行的時候?qū)?chuàng)建新對象,到最大對象數(shù)目,程序?qū)⒊霈F(xiàn)異常。

@Override
    public void returnObject(T obj) {
        PooledObject<T> p = allObjects.get(new IdentityWrapper<T>(obj));
        
 
        synchronized(p) {
            final PooledObjectState state = p.getState();
            if (state != PooledObjectState.ALLOCATED) {
                throw new IllegalStateException(
                        "Object has already been returned to this pool or is invalid");
            } else {
                p.markReturning(); // Keep from being marked abandoned
            }
        }

        long activeTime = p.getActiveTimeMillis();
   
        try {
            factory.passivateObject(p);
        } catch (Exception e1) {
            swallowException(e1);
              destroy(p);
              ensureIdle(1, false);
              updateStatsReturn(activeTime);
            return;
        }
        int maxIdleSave = getMaxIdle();
        if (isClosed() || maxIdleSave > -1 && maxIdleSave <= idleObjects.size()) {
            try {
                destroy(p);
            } catch (Exception e) {
                swallowException(e);
            }
        } else {
            if (getLifo()) {
                idleObjects.addFirst(p);
            } else {
                idleObjects.addLast(p);
            }
            if (isClosed()) {
                // Pool closed while object was being added to idle objects.
                // Make sure the returned object is destroyed rather than left
                // in the idle object pool (which would effectively be a leak)
                clear();
            }
        }
        updateStatsReturn(activeTime);
    }

從中我們可以看到一些destory object策略。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Java對象的生命周期分析 Java對象的生命周期大致包括三個階段: 對象的創(chuàng)建 對象的使用 對象的清 因此,對象...
    jiangmo閱讀 3,705評論 1 3
  • categories: Interviewdescription: 本文收集了一些經(jīng)典的Java面試題 1、面向?qū)?..
    我是阿喵醬閱讀 88,461評論 0 86
  • 多少人連個真心話都不敢講?連個真實感受都不能與人言,太害怕失去了,反而失去了自己,失去了自己,還有什么?建立的底座...
    縱情嬉戲天地間閱讀 261評論 0 0
  • 聽完別人的例會,聽到一句話,無效的信息,其實在浪費(fèi)溝通者的時間。 這一年我的狀態(tài)感始終在飄忽,非我,我甚至開玩笑慰...
    Sophia1022閱讀 405評論 0 0
  • 初次見她時,我剛踏上工作崗位。第一次踏上講臺,便是迎接滿滿一教室的新生,還有教室外面神色各異的家長?;蛟S,他們看出...
    離影疏落閱讀 540評論 3 3

友情鏈接更多精彩內(nèi)容