The Genericobjectpool and Generickeyedobjectpool of Commons-pool combat

Source: Internet
Author: User
Tags static class
The previous two articles say how to use the Commons-pool library simply, one problem to consider here is that in many cases our objects in the pool are heavier and most of the scarce resources, such as database connections, will be very resource if you keep some connections in the pool and do not return them. and is the utilization of these resources reduced, so how to better manage the pool of resources, Commons-pool provides a Genericobjectpool class, it's the emergence of the above problems will be solved. Also for the Genericobjectpool class, there is a corresponding Generickeyedobjectpool class.

Here's an example of speaking.

A connection class that can be imagined as a remote connection such as a database connection. This includes creating a connection, closing the connection, and a print method.

Package com.googlecode.garbagecan.commons.pool.sample3;

Import Org.slf4j.Logger;
Import org.slf4j.LoggerFactory;

public class MyConnection {
	
	private static Logger Logger = Loggerfactory.getlogger (myconnection.class);
	
	private String name;
	private Boolean connected;

	Public myconnection (String name) {
		this.name = name;
	}

	public void Connect () {
		this.connected = true;
		Logger.info (name + ":" + connected);
	}

	public void Close () {
		this.connected = false;
		Logger.info (name + ":" + connected);
	}

	public boolean isconnected () {return
		this.connected;
	}
	
	Public String GetName () {return
		this.name;
	}
	
	public void print () {
		logger.info (this.name);
	}
}
A poolableobjectfactory interface implementation class that provides Makeobject, Activateobject, Passivateobject, Validateobject, and Destroyobject methods.

Package com.googlecode.garbagecan.commons.pool.sample3;
Import Org.apache.commons.pool.PoolableObjectFactory;
Import Org.slf4j.Logger;

Import Org.slf4j.LoggerFactory; public class Myconnectionpoolableobjectfactory implements Poolableobjectfactory {private static Logger Logger = Loggerf
	
	Actory.getlogger (Myconnectionpoolableobjectfactory.class);
	
	private static int count = 0;
		Public Object Makeobject () throws Exception {myconnection myconn = new MyConnection (Generatename ());
		Logger.info (Myconn.getname ());
		Myconn.connect ();
	return myconn;
		public void Activateobject (Object obj) throws Exception {myconnection myconn = (myconnection) obj;
	Logger.info (Myconn.getname ());
		public void Passivateobject (Object obj) throws Exception {myconnection myconn = (myconnection) obj;
	Logger.info (Myconn.getname ());
		public boolean validateobject (Object obj) {myconnection myconn = (myconnection) obj;
		Logger.info (Myconn.getname ());
	return myconn.isconnected ();
}	
	public void Destroyobject (Object obj) throws Exception {myconnection myconn = (myconnection) obj;
		Logger.info (Myconn.getname ());
	Myconn.close ();
	Private synchronized String Generatename () {return "Conn_" + (++count); }
}
A test class

Package com.googlecode.garbagecan.commons.pool.sample3;
Import Org.apache.commons.pool.ObjectPool;
Import Org.apache.commons.pool.PoolableObjectFactory;
Import Org.apache.commons.pool.impl.GenericObjectPool;
Import Org.slf4j.Logger;

Import Org.slf4j.LoggerFactory;
	
	public class Test {private static Logger Logger = Loggerfactory.getlogger (Test.class);
		public static void Main (string[] args) {//test1 ();
		Test2 ();
	Test3 ();
		private static void Test1 () {Poolableobjectfactory factory = new Myconnectionpoolableobjectfactory ();
		Genericobjectpool.config Config = new Genericobjectpool.config ();
		Config.lifo = false;
		Config.maxactive = 5;
		Config.maxidle = 5;
		Config.minidle = 1;
		
		config.maxwait = 5 * 1000;
		Objectpool pool = new Genericobjectpool (factory, config);
			for (int i = 0; i < i++) {thread thread = new Thread (new MyTask (pool));
		Thread.Start ();
	}//closepool (pool); private static void Test2 () {Poolableobjectfactory Factory= new Myconnectionpoolableobjectfactory ();
		Genericobjectpool.config Config = new Genericobjectpool.config ();
		Config.lifo = false;
		Config.maxactive = 5;
		Config.maxidle = 5;
		Config.minidle = 1;

		config.maxwait = 20 * 1000;
		Objectpool pool = new Genericobjectpool (factory, config);
			for (int i = 0; i < i++) {thread thread = new Thread (new MyTask (pool));
		Thread.Start ();
	}//closepool (pool);
		private static void Test3 () {Poolableobjectfactory factory = new Myconnectionpoolableobjectfactory ();
		Genericobjectpool.config Config = new Genericobjectpool.config ();
		Config.lifo = false;
		Config.maxactive = 5;
		Config.maxidle = 0;
		Config.minidle = 0;

		config.maxwait =-1;
		Objectpool pool = new Genericobjectpool (factory, config);
		Thread thread = new Thread (new MyTask (pool));

		Thread.Start ();
		try {thread.sleep (60L * 1000L);
		catch (Exception e) {e.printstacktrace ();
	}//closepool (pool); } private static void Closepool (OBJECTPOol Pool) {try {pool.close ();
		catch (Exception e) {e.printstacktrace ();
		
		} private static Class MyTask implements Runnable {private Objectpool pool;
		Public MyTask (Objectpool pool) {this.pool = pool;
			public void Run () {myconnection myconn = null;
				try {myconn = (myconnection) pool.borrowobject ();
				try {myconn.print ();
					catch (Exception ex) {pool.invalidateobject (myconn);
				myconn = null;
			} thread.sleep (10L * 1000L);
			catch (Exception ex) {Logger.error ("Cannot borrow connection from pool.", ex);
					finally {if (myconn!= null) {try {pool.returnobject (myconn);
					catch (Exception ex) {Logger.error ("Cannot return connection from pool.", ex); }
				}
			}
		}
	}
}
It includes three methods, testing three kinds of cases respectively;
The class contains an internal class that implements the Runnable interface to initiate the use of the connection class that several threads simulate, and to sleep for 10 seconds in the Run method to be as realistic as possible; First run the test method Test1 () can see that When the 10 threads request the connection class, the first 5 can be well fetched, but the next 5 threads cannot get the connection and throw the exception because of "config.maxactive = 5;" and "config.maxwait = 5 * 1000;" At work, because the maximum active connection is configured with 5, and the wait time for subsequent requests that do not have a valid connection is 5 seconds, the following five lines in the Test1 method thread after 5 seconds, all throw an exception, indicating that the connection cannot be applied. The following runs the Test2 () method, in test2 "config.maxwait = 20 * 1000;" Changed to 20 seconds, and each thread in our program use the connection will be used for 10 seconds, so the next five threads after waiting for 10 seconds after the full access to the connection, so the program will eventually run successfully. Then look at the Test3 () method, where the Maxidle and Minidle are changed to 0, that is, when the connection is not immediately real return connection, for the database connection is to shut down the physical connection, and maxwait to 1, that is, if no application to the connection will always wait, run Test3 () method, observing the log, you can see that the program calls the Myconnectionpoolableobjectfactory.destroyobject () and Myconnection.close () methods to destroy the object after the user connects the object. So if you use such a configuration, it is equivalent to a physical connection every time, and then close the connection when you are done with it. Of course, this is an extreme example of the fact that Maxidle and Minidle are not set to 0.
In fact, there are a lot of configuration parameters for the Genericobjectpool.config class and the Generickeyedobjectpool.config class, but here are just a few of the simplest common ones that can be referenced in the official documentation.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.