Example usage for org.apache.commons.pool.impl GenericObjectPool WHEN_EXHAUSTED_BLOCK

List of usage examples for org.apache.commons.pool.impl GenericObjectPool WHEN_EXHAUSTED_BLOCK

Introduction

In this page you can find the example usage for org.apache.commons.pool.impl GenericObjectPool WHEN_EXHAUSTED_BLOCK.

Prototype

byte WHEN_EXHAUSTED_BLOCK

To view the source code for org.apache.commons.pool.impl GenericObjectPool WHEN_EXHAUSTED_BLOCK.

Click Source Link

Document

A "when exhausted action" type indicating that when the pool is exhausted (i.e., the maximum number of active objects has been reached), the #borrowObject method should block until a new object is available, or the #getMaxWait maximum wait time has been reached.

Usage

From source file:com.verisign.epp.pool.EPPSessionPool.java

/**
 * Initialize a single pool using configuration values defined by 
 * {@link com.verisign.epp.util.Environment} class.  The 
 * {@link com.verisign.epp.util.Environment} class and logging must 
 * be initialized before calling this method.  
 * /*from  w ww. j a v a  2  s  .  c o m*/
 * @throws EPPSessionPoolException On error
 */
private void initSinglePool() throws EPPSessionPoolException {
    log.debug("initSinglePool: enter");

    // Get configuration settings for pool
    try {
        String theValue;

        // clientId
        this.clientId = this.getProperty("clientId");
        if (this.clientId == null) {
            log.error("EPPSessionPool.initSinglePool(): clientId not defined");
            throw new EPPSessionPoolException("clientId not defined");
        }

        // password
        this.password = this.getProperty("password");
        if (this.password == null) {
            log.error("EPPSessionPool.initSinglePool(): password not defined");
            throw new EPPSessionPoolException("password not defined");
        }

        // absoluteTimeout
        theValue = this.getProperty("absoluteTimeout");
        if (theValue != null)
            this.absoluteTimeout = Long.parseLong(theValue);
        else
            this.absoluteTimeout = DEFAULT_ABSOLUTE_TIMEOUT;
        log.info("init(): absolute timeout = " + this.absoluteTimeout + " ms");

        // idleTimeout
        theValue = this.getProperty("idleTimeout");
        if (theValue != null)
            this.idleTimeout = Long.parseLong(theValue);
        else
            this.idleTimeout = DEFAULT_IDLE_TIMEOUT;
        log.info("init(): idle timeout = " + this.idleTimeout + " ms");

        // poolableClassName
        theValue = this.getProperty("poolableClassName");
        if (theValue == null) {
            log.error("EPPSessionPool.initSinglePool(): EPP.SessionPool.poolableClassName not defined");
            throw new EPPSessionPoolException("EPP.SessionPool.poolableClassName not defined");
        }
        log.info("init(): poolable class name = " + theValue);

        try {
            this.factory = (EPPSessionPoolableFactory) Class.forName(theValue).newInstance();
        } catch (Exception ex) {
            log.error("EPPSessionPool.initSinglePool(): Exception creating instance of class " + theValue + ": "
                    + ex);
            throw new EPPSessionPoolException("Exception creating instance of class " + theValue + ": " + ex);
        }

        // Ensure minEvictableIdleTimeMillis is disabled
        this.config.minEvictableIdleTimeMillis = 0;

        // maxIdle
        theValue = this.getProperty("maxIdle");
        if (theValue != null)
            this.config.maxIdle = Integer.parseInt(theValue);
        else
            this.config.maxIdle = DEFAULT_MAX_IDLE;
        log.info("initSinglePool(): max idle = " + this.config.maxIdle);

        // maxActive
        theValue = this.getProperty("maxActive");
        if (theValue != null)
            this.config.maxActive = Integer.parseInt(theValue);
        else
            this.config.maxActive = DEFAULT_MAX_ACTIVE;
        log.info("initSinglePool(): max active = " + this.config.maxActive);

        // initMaxActive
        theValue = this.getProperty("initMaxActive");
        if (theValue != null)
            this.initMaxActive = (Boolean.valueOf(theValue)).booleanValue();
        else
            this.initMaxActive = DEFAULT_INIT_MAX_ACTIVE;
        log.info("initSinglePool(): init max active = " + this.initMaxActive);

        // borrowRetries
        theValue = this.getProperty("borrowRetries");
        if (theValue != null)
            this.borrowRetries = Integer.parseInt(theValue);
        else
            this.borrowRetries = DEFAULT_BORROW_RETRIES;
        log.info("initSinglePool(): borrow retries = " + this.borrowRetries);

        // maxWait
        theValue = this.getProperty("maxWait");
        if (theValue != null)
            this.config.maxWait = Integer.parseInt(theValue);
        else
            this.config.maxWait = DEFAULT_MAX_WAIT;
        log.info("initSinglePool(): max wait = " + this.config.maxWait);

        // minIdle
        theValue = this.getProperty("minIdle");
        if (theValue != null)
            this.config.minIdle = Integer.parseInt(theValue);
        else
            this.config.minIdle = DEFAULT_MIN_IDLE;
        log.info("initSinglePool(): min idle = " + this.config.minIdle);

        // numTestsPerEvictionRun
        this.config.numTestsPerEvictionRun = -1; // This will cause all session to be tested

        // testOnBorrow
        this.config.testOnBorrow = false;

        // testOnReturn
        this.config.testOnReturn = false;

        // testWhileIdle
        this.config.testWhileIdle = true;

        // timeBetweenEvictionRunsMillis
        theValue = this.getProperty("timeBetweenEvictionRunsMillis");
        if (theValue != null)
            this.config.timeBetweenEvictionRunsMillis = Long.parseLong(theValue);
        else
            this.config.timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
        log.info("initSinglePool(): time between eviction runs = " + this.config.timeBetweenEvictionRunsMillis
                + " ms");

        // whenExhaustedAction
        this.config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;

        // serverName
        this.serverName = EPPEnv.getServerName();
        log.info("initSinglePool(): serverName = " + this.serverName);

        // serverPort
        theValue = Environment.getEnv("EPP.ServerPort");
        if (theValue != null)
            this.serverPort = new Integer(theValue);
        log.info("initSinglePool(): serverPort = " + this.serverPort);

        // clientHost
        this.clientHost = EPPEnv.getClientHost();
        log.info("initSinglePool(): clientHost = " + this.clientHost);

    } catch (EPPEnvException ex) {
        log.error("EPPSessionPool.initSinglePool(): EPPEnvException referencing Environment property: " + ex);
        throw new EPPSessionPoolException("EPPEnvException referencing Environment property: " + ex);
    } catch (EnvException ex) {
        log.error("EPPSessionPool.initSinglePool(): EnvException referencing Environment property: " + ex);
        throw new EPPSessionPoolException("EnvException referencing Environment property: " + ex);
    }

    // Set factory required attributes
    this.factory.setAbsoluteTimeout(this.absoluteTimeout);
    this.factory.setIdleTimeout(this.idleTimeout);
    this.factory.setClientId(this.clientId);
    this.factory.setPassword(this.password);
    this.factory.setServerName(this.serverName);
    this.factory.setServerPort(this.serverPort);
    this.factory.setClientHost(this.clientHost);

    this.init(this.factory, this.config);

    // Pre-initialize maxActive sessions in pool?
    if (this.initMaxActive && this.config.maxActive > 0) {
        log.info("initSinglePool(): Pre-initialize maxActive (" + this.config.maxActive + ") sessions");

        EPPSession theSessions[] = new EPPSession[this.config.maxActive];

        // Borrow maxActive sessions from pool
        for (int i = 0; i < this.config.maxActive; i++) {

            try {
                theSessions[i] = this.borrowObject();
                log.info("initSinglePool(): Pre-initialized session #" + (i + 1));
            } catch (EPPSessionPoolException ex) {
                log.error("initSinglePool(): Failure to pre-initialize session #" + (i + 1) + ": " + ex);
            }
        }

        // Return maxActive sessions back to pool
        for (int i = 0; i < this.config.maxActive; i++) {
            if (theSessions[i] != null) {
                this.returnObject(theSessions[i]);
                theSessions[i] = null;
            }
        }

    }

    log.debug("initSinglePool: exit");
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testTimeoutNoLeak() throws Exception {
    pool.setMaxActive(2);/*ww  w .  j a  v a2s  . c  o  m*/
    pool.setMaxWait(10);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    Object obj = pool.borrowObject();
    Object obj2 = pool.borrowObject();
    try {
        pool.borrowObject();
        fail("Expecting NoSuchElementException");
    } catch (NoSuchElementException ex) {
        // xpected
    }
    pool.returnObject(obj2);
    pool.returnObject(obj);

    obj = pool.borrowObject();
    obj2 = pool.borrowObject();
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testMaxActiveUnderLoad() {
    // Config//from www  .  j av a2 s. co m
    int numThreads = 199; // And main thread makes a round 200.
    int numIter = 20;
    int delay = 25;
    int maxActive = 10;

    SimpleFactory factory = new SimpleFactory();
    factory.setMaxActive(maxActive);
    pool.setFactory(factory);
    pool.setMaxActive(maxActive);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setTimeBetweenEvictionRunsMillis(-1);

    // Start threads to borrow objects
    TestThread[] threads = new TestThread[numThreads];
    for (int i = 0; i < numThreads; i++) {
        // Factor of 2 on iterations so main thread does work whilst other
        // threads are running. Factor of 2 on delay so average delay for
        // other threads == actual delay for main thread
        threads[i] = new TestThread(pool, numIter * 2, delay * 2);
        Thread t = new Thread(threads[i]);
        t.start();
    }
    // Give the threads a chance to start doing some work
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // ignored
    }

    for (int i = 0; i < numIter; i++) {
        Object obj = null;
        try {
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                // ignored
            }
            obj = pool.borrowObject();
            // Under load, observed _numActive > _maxActive
            if (pool.getNumActive() > pool.getMaxActive()) {
                throw new IllegalStateException("Too many active objects");
            }
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                // ignored
            }
        } catch (Exception e) {
            // Shouldn't happen
            e.printStackTrace();
            fail("Exception on borrow");
        } finally {
            if (obj != null) {
                try {
                    pool.returnObject(obj);
                } catch (Exception e) {
                    // Ignore
                }
            }
        }
    }

    for (int i = 0; i < numThreads; i++) {
        while (!(threads[i]).complete()) {
            try {
                Thread.sleep(500L);
            } catch (InterruptedException e) {
                // ignored
            }
        }
        if (threads[i].failed()) {
            fail("Thread " + i + " failed: " + threads[i]._error.toString());
        }
    }
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testSettersAndGetters() throws Exception {
    GenericObjectPool pool = new GenericObjectPool();
    {/*w w  w .  ja  v  a2 s . c o  m*/
        pool.setFactory(new SimpleFactory());
    }
    {
        pool.setMaxActive(123);
        assertEquals(123, pool.getMaxActive());
    }
    {
        pool.setMaxIdle(12);
        assertEquals(12, pool.getMaxIdle());
    }
    {
        pool.setMaxWait(1234L);
        assertEquals(1234L, pool.getMaxWait());
    }
    {
        pool.setMinEvictableIdleTimeMillis(12345L);
        assertEquals(12345L, pool.getMinEvictableIdleTimeMillis());
    }
    {
        pool.setNumTestsPerEvictionRun(11);
        assertEquals(11, pool.getNumTestsPerEvictionRun());
    }
    {
        pool.setTestOnBorrow(true);
        assertTrue(pool.getTestOnBorrow());
        pool.setTestOnBorrow(false);
        assertTrue(!pool.getTestOnBorrow());
    }
    {
        pool.setTestOnReturn(true);
        assertTrue(pool.getTestOnReturn());
        pool.setTestOnReturn(false);
        assertTrue(!pool.getTestOnReturn());
    }
    {
        pool.setTestWhileIdle(true);
        assertTrue(pool.getTestWhileIdle());
        pool.setTestWhileIdle(false);
        assertTrue(!pool.getTestWhileIdle());
    }
    {
        pool.setTimeBetweenEvictionRunsMillis(11235L);
        assertEquals(11235L, pool.getTimeBetweenEvictionRunsMillis());
    }
    {
        pool.setSoftMinEvictableIdleTimeMillis(12135L);
        assertEquals(12135L, pool.getSoftMinEvictableIdleTimeMillis());
    }
    {
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_BLOCK, pool.getWhenExhaustedAction());
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_FAIL);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_FAIL, pool.getWhenExhaustedAction());
        pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
        assertEquals(GenericObjectPool.WHEN_EXHAUSTED_GROW, pool.getWhenExhaustedAction());
    }
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericKeyedObjectPool.java

@Test
// @Schedules({/* w w w  . j  av a 2  s. c om*/
//     @Schedule(name = "BorrowOneBeforeTwo", value = "[beforeBorrow:afterBorrow]@borrowThread -> borrowTwo@main")})
public void testBlockedKeyDoesNotBlockPoolImproved() throws Exception {
    SimpleFactory factory = new SimpleFactory();
    GenericKeyedObjectPool pool = new GenericKeyedObjectPool(factory);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setMaxActive(1);
    pool.setMaxTotal(-1);

    // Borrow with one key
    Object obj = pool.borrowObject("one");

    // Borrow again with same key, should be blocked
    Runnable simple = new SimpleTestThread(pool, "one");
    Thread borrowThread = new Thread(simple, "borrowThread");
    borrowThread.start();

    // Wait for sometime and borrow with another key
    // Should not block
    Thread.sleep(1000);
    pool.borrowObject("two");
    assertEquals(1, pool.getNumActive("one"));
    assertEquals(1, pool.getNumActive("two"));

    // Unblock and join the thread
    pool.returnObject("one", obj);
    borrowThread.join();
    assertEquals(0, pool.getNumActive("one"));
    assertEquals(1, pool.getNumActive("two"));
}

From source file:edu.illinois.imunit.examples.apache.pool.TestGenericKeyedObjectPool.java

@Test
@Schedules({/*from w w  w . java  2  s  .  c  o m*/
        @Schedule(name = "BorrowOneBeforeTwo", value = "[beforeBorrow:afterBorrow]@borrowThread -> borrowTwo@main") })
public void testBlockedKeyDoesNotBlockPoolImproved() throws Exception {
    SimpleFactory factory = new SimpleFactory();
    GenericKeyedObjectPool pool = new GenericKeyedObjectPool(factory);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setMaxActive(1);
    pool.setMaxTotal(-1);

    // Borrow with one key
    Object obj = pool.borrowObject("one");

    // Borrow again with same key, should be blocked
    Runnable simple = new SimpleTestThread(pool, "one");
    Thread borrowThread = new Thread(simple, "borrowThread");
    borrowThread.start();

    // Wait for sometime and borrow with another key
    // Should not block
    Thread.sleep(1000);
    fireEvent("borrowTwo");
    pool.borrowObject("two");
    assertEquals(1, pool.getNumActive("one"));
    assertEquals(1, pool.getNumActive("two"));

    // Unblock and join the thread
    pool.returnObject("one", obj);
    borrowThread.join();
    assertEquals(0, pool.getNumActive("one"));
    assertEquals(1, pool.getNumActive("two"));
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericKeyedObjectPool.java

public void testBlockedKeyDoesNotBlockPool() throws Exception {
    SimpleFactory factory = new SimpleFactory();
    GenericKeyedObjectPool pool = new GenericKeyedObjectPool(factory);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setMaxWait(5000);// w w w  . j a  va  2  s .co m
    pool.setMaxActive(1);
    pool.setMaxTotal(-1);
    pool.borrowObject("one");
    long start = System.currentTimeMillis();
    // Needs to be in a separate thread as this will block
    Runnable simple = new SimpleTestThread(pool, "one");
    Thread borrowThread = new Thread(simple, "borrowThread");
    borrowThread.start();
    // This should be almost instant. If it isn't it means this thread got
    // stuck behind the thread created above which is bad.
    // Give other thread a chance to start        
    //Thread.sleep(1000);    
    pool.borrowObject("two");
    long end = System.currentTimeMillis();
    // If it fails it will be more than 4000ms (5000 less the 1000 sleep)
    // If it passes it should be almost instant
    // Use 3000ms as the threshold - should avoid timing issues on most
    // (all? platforms)
    //assertTrue ((end-start) < 4000);

}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testBorrowObjectFairness() {
    // Config/* w  w  w .  j  a va  2 s .com*/
    int numThreads = 30;
    int maxActive = 10;

    SimpleFactory factory = new SimpleFactory();
    factory.setMaxActive(maxActive);
    pool.setFactory(factory);
    pool.setMaxActive(maxActive);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setTimeBetweenEvictionRunsMillis(-1);

    // Start threads to borrow objects
    TestThread[] threads = new TestThread[numThreads];
    for (int i = 0; i < numThreads; i++) {
        threads[i] = new TestThread(pool, 1, 2000, false, String.valueOf(i % maxActive));
        Thread t = new Thread(threads[i]);
        t.start();
        // Short delay to ensure threads start in correct order
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            fail(e.toString());
        }
    }

    // Wait for threads to finish
    for (int i = 0; i < numThreads; i++) {
        while (!(threads[i]).complete()) {
            try {
                Thread.sleep(500L);
            } catch (InterruptedException e) {
                // ignored
            }
        }
        if (threads[i].failed()) {
            fail("Thread " + i + " failed: " + threads[i]._error.toString());
        }
    }
}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

/**
 * On first borrow, first object fails validation, second object is OK.
 * Subsequent borrows are OK. This was POOL-152.
 *//*  ww w  .ja va 2 s. c o m*/
public void testBrokenFactoryShouldNotBlockPool() {
    int maxActive = 1;

    SimpleFactory factory = new SimpleFactory();
    factory.setMaxActive(maxActive);
    pool.setFactory(factory);
    pool.setMaxActive(maxActive);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setTestOnBorrow(true);

    // First borrow object will need to create a new object which will fail
    // validation.
    Object obj = null;
    Exception ex = null;
    factory.setValid(false);
    try {
        obj = pool.borrowObject();
    } catch (Exception e) {
        ex = e;
    }
    // Failure expected
    assertNotNull(ex);
    assertTrue(ex instanceof NoSuchElementException);
    assertNull(obj);

    // Configure factory to create valid objects so subsequent borrows work
    factory.setValid(true);

    // Subsequent borrows should be OK
    try {
        obj = pool.borrowObject();
    } catch (Exception e1) {
        fail();
    }
    assertNotNull(obj);
    try {
        pool.returnObject(obj);
    } catch (Exception e) {
        fail();
    }

}

From source file:edu.illinois.enforcemop.examples.apache.pool.TestGenericObjectPool.java

public void testMaxWaitMultiThreaded() throws Exception {
    final long maxWait = 500; // wait for connection
    final long holdTime = 2 * maxWait; // how long to hold connection
    final int threads = 10; // number of threads to grab the object initially
    SimpleFactory factory = new SimpleFactory();
    GenericObjectPool pool = new GenericObjectPool(factory);
    pool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK);
    pool.setMaxWait(maxWait);/*from  ww w.  j a  v a 2s.c  om*/
    pool.setMaxActive(threads);
    // Create enough threads so half the threads will have to wait
    WaitingTestThread wtt[] = new WaitingTestThread[threads * 2];
    for (int i = 0; i < wtt.length; i++) {
        wtt[i] = new WaitingTestThread(pool, holdTime);
    }
    long origin = System.currentTimeMillis() - 1000;
    for (int i = 0; i < wtt.length; i++) {
        wtt[i].start();
    }
    int failed = 0;
    for (int i = 0; i < wtt.length; i++) {
        wtt[i].join();
        if (wtt[i]._thrown != null) {
            failed++;
        }
    }
    if (DISPLAY_THREAD_DETAILS || wtt.length / 2 != failed) {
        System.out.println("MaxWait: " + maxWait + " HoldTime: " + holdTime + " MaxActive: " + threads
                + " Threads: " + wtt.length + " Failed: " + failed);
        for (int i = 0; i < wtt.length; i++) {
            WaitingTestThread wt = wtt[i];
            System.out.println("Preborrow: " + (wt.preborrow - origin) + " Postborrow: "
                    + (wt.postborrow != 0 ? wt.postborrow - origin : -1) + " BorrowTime: "
                    + (wt.postborrow != 0 ? wt.postborrow - wt.preborrow : -1) + " PostReturn: "
                    + (wt.postreturn != 0 ? wt.postreturn - origin : -1) + " Ended: " + (wt.ended - origin)
                    + " ObjId: " + wt.objectId);
        }
    }
    assertEquals("Expected half the threads to fail", wtt.length / 2, failed);
}