com.fjn.helper.frameworkex.apache.commons.pool.connectionPool.ConnectionManager.java Source code

Java tutorial

Introduction

Here is the source code for com.fjn.helper.frameworkex.apache.commons.pool.connectionPool.ConnectionManager.java

Source

/*
 *
 *  Copyright 2018 FJN Corp.
 *
 *  Licensed 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.
 *
 *  Author                        Date                       Issue
 *  fs1194361820@163.com          2015-01-01                 Initial Version
 *
 */

package com.fjn.helper.frameworkex.apache.commons.pool.connectionPool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;

public class ConnectionManager {
    private ObjectPool pool;
    private ConnectionFactory connFactory;
    private ConnectionPoolFactory connPoolFactory;

    /**
     *
     * @param maxNum
     * @param maxIdleCount
     * @param minIdleCount
     * @param maxWaitTime
     *
     */
    public void initConnectionPool(int maxNum, int maxIdleCount, int minIdleCount, long maxWaitTime) {
        int maxActive = maxNum;
        byte whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION;
        long maxWait = maxWaitTime;
        int maxIdle = maxIdleCount;
        int minIdle = minIdleCount;
        boolean testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW;
        boolean testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN;
        long timeBetweenEvictionRunsMillis = GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
        int numTestsPerEvictionRun = GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
        long minEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
        boolean testWhileIdle = GenericObjectPool.DEFAULT_TEST_WHILE_IDLE;
        long softMinEvictableIdleTimeMillis = GenericObjectPool.DEFAULT_SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
        boolean lifo = GenericObjectPool.DEFAULT_LIFO;
        connPoolFactory = new ConnectionPoolFactory(connFactory, maxActive, whenExhaustedAction, maxWait, maxIdle,
                minIdle, testOnBorrow, testOnReturn, timeBetweenEvictionRunsMillis, numTestsPerEvictionRun,
                minEvictableIdleTimeMillis, testWhileIdle, softMinEvictableIdleTimeMillis, lifo);

    }

    public static void main(String[] args) {
        final ConnectionManager mgr = new ConnectionManager();
        mgr.connFactory = new ConnectionFactory();
        mgr.connFactory.setDriverClass("com.mysql.jdbc.Driver");
        mgr.connFactory.setPassword("mysql");
        mgr.connFactory.setUsername("mysql");
        mgr.connFactory.setUrl("url:localhost:3306"); // ?URL

        mgr.initConnectionPool(1000, 50, 5, 1000 * 60);
        mgr.pool = mgr.connPoolFactory.createPool();

        final AtomicInteger count = new AtomicInteger(0);

        int threadNum = Runtime.getRuntime().availableProcessors();
        ExecutorService client = Executors.newFixedThreadPool(threadNum);
        for (int i = 0; i < threadNum; i++) {
            client.submit(new Runnable() {
                @Override
                public void run() {
                    while (true && count.get() < 100) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }
                        Connection connection = null;

                        try {
                            connection = (Connection) mgr.pool.borrowObject();
                            try {

                                int value = count.incrementAndGet();
                                if (value < 100) {
                                    String threadName = Thread.currentThread().getName();

                                    int activeNum = mgr.pool.getNumActive();
                                    int idleNum = mgr.pool.getNumIdle();
                                    String content = "ThreadName: " + threadName + "\t SQL: "
                                            + "insert into tableA ( ct ) values ('" + value + "'); \t activeNum="
                                            + activeNum + "\t idleNum=" + idleNum;
                                    System.out.println(content);
                                }

                            } catch (Exception e) {
                                mgr.pool.invalidateObject(connection);
                                connection = null;
                            } finally {
                                // make sure the object is returned to the pool
                                if (null != connection) {
                                    mgr.pool.returnObject(connection);
                                }
                            }
                        } catch (Exception e) {
                            // failed to borrow an object
                        }

                    }
                }
            });
        }
    }

}