Java-socket connection pool

Source: Internet
Author: User

1: socketadapter class. This class inherits the socket and reloads the close method of the socket class, so that when the user closes the socket, we do not close it but put it inside the connection pool.
Package com.tar Ena. socketpool;
Import java.net .*;
Import java. Io. ioexception;
/**
* <P> simple socket connection implementation </P>
* <P> Description: </P>
* <P> copyright: Copyright tarena (c) 2005 </P>
* <P> company: tarena </P>
* @ Author chengxing
* @ Version 1.0
*/
Public class connectionadapter extends socket {
/**
* Connection status
*/
Private Boolean status = true;
/**
* Default constructor
*/
Public connectionadapter (){
Super ();
}
Public connectionadapter (string host, int port) throws unknownhostexception, ioexception {
Super (host, Port );
}
/**
* Determines whether the connection is idle.
* @ Return Boolean returns true when idle; otherwise, false
*/
Public Boolean isfree (){
Return status;
}
/**
* When using this connection, set the status to false (busy)
*/
Public void setbusy (){
This. Status = false;
}
/**
* When the client closes the connection, the status is set to true (idle)
*/
Public void close (){
System. Out. println (close: Set the status is free );
Status = true;
}
Public void destroy (){
// Close socket connection
Close ();
// System. Out. println (close success );
}
}
The second type is the Connection Manager.
Package com.tar Ena. socketpool;

Import java. Lang. Reflect .*;
Import java. util. properties;
/**
* <P> Connection Manager </P>
* <P> copyright: Copyright tarena (c) 2005 </P>
* <P> company: tarena </P>
* @ Author chengxing
* @ Version 1.0
*/
Public class connectionmanager {
// Test Program Default connection pool implementation class
Public static final string provider_class‑com.tar Ena. socketpool. myconnectionprovider;
// Default IP address of the Test Program
Public static final string host = 127.0.0.1;
// Default port number of the Test Program
Public static final string port = 9880;
/**
* Register the static anonymous block of the hook Program
*/
Static {
// Increase the cycle for releasing hook control resources
Runtime runtime = runtime. getruntime ();
Class C = runtime. getclass ();
Try {
Method M = C. getmethod (addshutdownhook, new class [] {thread. Class });
M. Invoke (runtime, new object [] {New shutdownthread ()});
}
Catch (nosuchmethodexception e ){
E. printstacktrace ();
// Ignore -- the user might not be running JDK 1.3 or later.
}
Catch (exception e ){
E. printstacktrace ();
}
}
/**
* Default constructor
*/
Public connectionmanager (){
}
/**
* Obtain and initialize a connection pool.
* The implementation class of the connection pool is passed in through system parameters, and through the command line-dconnectionprovider = yourimplclass
* If no implementation is specified, the system default implementation class is used.
* The list of parameters passed in through the command line is as follows:
* Host Name of the recipient-dhost = 192.168.0.200
* Peer port-dport = 9880
* Minimum connections-dmax_style = 'font-size: 10px '0
* Maximum number of links-dmin_style = 'font-size: 14px '0
* The preceding values can be changed, but the parameters cannot be changed,
* The maximum number of connections and the minimum number of connections can be omitted. The default values are 20 and 10, respectively.
* @ Return connectionprovider
*/
Public static connectionprovider getconnectionprovider () throws exception {
String provider_class = system. getproperty (connectionprovider );
If (provider_class = NULL) provider_class = provider_class;

String host = system. getproperty (host );
If (host = NULL) host = host;

String Port = system. getproperty (port );
If (Port = NULL) Port = port;

String max_size = system. getproperty (max_size );
String min_size = system. getproperty (min_size );

Properties pro = new properties ();
Pro. setproperty (connectionprovider. server_ip, host );
Pro. setproperty (connectionprovider. server_port, Port );
If (max_size! = NULL) Pro. setproperty (connectionprovider. max_size, max_size );
If (min_size! = NULL) Pro. setproperty (connectionprovider. min_size, min_size );
// Obtain the implementation class through reflection
System. Out. println (provider_class );
System. Out. Flush ();
Class provider_impl = Class. forname (provider_class );
// Uses the static callback method because it is in the list mode.
Method M = provider_impl.getmethod (newinstance, new class [] {java. util. properties. Class });
Connectionprovider provider = NULL;
Try {
Provider = (connectionprovider) M. Invoke (provider_impl, new object [] {pro });
} Catch (exception e ){
E. printstacktrace ();
}

Return provider;
}
/**
*
* <P> A hook thread: call to cancel the connection pool at the end of the program </P>
* <P> Description: </P>
* <P> copyright: Copyright tarena (c) 2005 </P>
* <P> company: tarena </P>
* @ Author chengxing
* @ Version 1.0
*/
Private Static class shutdownthread extends thread {
Public void run (){
Try {
Connectionprovider provider = connectionmanager. getconnectionprovider ();
If (provider! = NULL ){
Provider. Destroy ();
}
} Catch (exception e ){
E. printstacktrace ();
}
}
}

}

The third class is the interface definition of the connection pool.
Package com.tar Ena. socketpool;

Import java.net .*;
Import java. util .*;
Import java. Io. ioexception;

/**
*
* <P> defined abstract classes. All subclasses must be implemented in the list mode,
* The unified method is public connectionprovider newinstance ();
* Connects to the abstract interface of the provisioner. Every subclass that implements it should preferably be a JavaBean,
* In this way, the method can be controlled by the outside world </P>
* @ See jivebeaninfo
* <P> copyright: Copyright tarena (c) 2005 </P>
* <P> company: tarena </P>
* @ Author chengxing
* @ Version 1.0
*/
Public interface
Connectionprovider {
Public static final string server_ip = server_ip_address;
Public static final string server_port = server_ip_port;
Public static final string max_size = max_size;
Public static final string min_size = min_size;

/**
* Determine whether a connection exists in the connection pool.
* @ Return True returns true if a connection exists. Otherwise, false is returned.
*/
Public Boolean ispooled ();

/**
* When this method is called, a socket is provided.
* @ See socket
* @ Return socket A connection object.
*/
Public socket getconnection () throws java.net. socketexception;

/**
* Connection pool Initialization
*/
Public void Init () throws unknownhostexception, ioexception;

/**
* Connection pool restart
*/
Public void restart () throws unknownhostexception, ioexception;

/**
* Log out of the Connection Pool
*/
Public void destroy ();
}
The fourth class is myconnectionprovider, which is a simple implementation of a self-written connection pool.
Package com.tar Ena. socketpool;

Import java. util .*;
Import java.net .*;
Import java.net. socketexception;
Import java. Io. ioexception;

/**
*
* <P> This is a simple implementation of the Connection Manager </P>
* <P> Description: implements the interface connectionprovider </P>
* <P> copyright: Copyright tarena (c) 2005 </P>
* <P> company: tarena </P>
* @ Author chengxing
* @ Version 1.0
*/
Public class myconnectionprovider
Implements connectionprovider {

Private Properties pro = NULL;
Private Static connectionprovider provider = NULL;
Private Static object object_lock = new object ();
Private string IP;
Private string port;

/**
* Default maximum number of connections
*/
Private int max_size = 20;

/**
* Default minimum connections
*/
Private int min_size = 10;

/**
* Socket connection pool Array
*/
Private connectionadapter [] socketpool = NULL;

/**
* Initialize the connection pool when constructing an object.
* @ Throws unknownhostexception unknown host exception
* @ Throws ioexception
*/
Private myconnectionprovider (properties Pro) throws unknownhostexception,
Ioexception {
IP = pro. getproperty (server_ip );
Port = pro. getproperty (server_port );
String max_size_s = pro. getproperty (max_size );
String min_size_s = pro. getproperty (min_size );
If (max_size_s! = NULL ){
Max_size = integer. parseint (max_size_s );
}
If (min_size_s! = NULL ){
Min_size = integer. parseint (min_size_s );
}

Init (); // initialize the connection pool when constructing an object
}

/**
* Determine whether the pool has been completed
* @ Return Boolean If pooling returns true, otherwise false.
*/
Public Boolean ispooled (){
If (socketpool! = NULL ){
Return true;
}
Else return false;
}

/**
* Returns a connection.
* @ Return a connection object.
*/
Public socket getconnection (){
Socket S = NULL;
For (INT I = 0; I <socketpool. length; I ++ ){
If (socketpool [I]! = NULL ){
// If there is an idle connection, a idle connection is returned. If not, the loop continues.
If (socketpool [I]. isfree ()){
S = socketpool [I];
Return S;
}
Else continue;
}
Else {// If the connection is null, the minimum number of connections is exceeded and the connection is regenerated.
Try {
S = socketpool [I] = new connectionadapter (IP, integer. parseint (port ));
}
Catch (exception e ){
// Never throw
}
}
}
// If the connection is still empty, the maximum number of connections is exceeded.
If (S = NULL ){
Try {// generate a normal connection, which is closed by the client and released by the connection pool.
S = new socket (IP, integer. parseint (port ));
}
Catch (exception e) {// This exception will never be thrown
}
}
Return S;
}

/**
* Initialize the connection pool
* @ Throws unknownhostexception the Host IP address cannot be found
* @ Throws ioexception no server listening on this port number
*/
Public void Init () throws unknownhostexception, ioexception {

Socketpool = new connectionadapter [max_size];
For (INT I = 0; I <min_size; I ++ ){
Socketpool [I] = new connectionadapter (IP, integer. parseint (port ));
System. Out. Print (.);
}
System. Out. println ();
System. Out. println (system init success ....);
}

/**
* Restart the connection pool.
* @ Throws unknownhostexception
* @ Throws ioexception
*/
Public void restart () throws unknownhostexception, ioexception {
Destroy ();
Init ();
}

/**
* Log out of the connection pool.
*/
Public void destroy (){
For (INT I = 0; I <socketpool. length; I ++ ){
If (socketpool [I]! = NULL ){
Connectionadapter adapter = (connectionadapter) socketpool [I];
Adapter. Destroy ();
System. Out. Print (.);
}
}
System. Out. println (\ ndestory success ....);
}
/**
* Static Method: generate the object implemented by this connection pool
* @ Param pro properties encapsulate all parameters required for this connection pool
* @ Throws unknownhostexception the host cannot be found
* @ Throws ioexception cannot establish a connection with the server
* @ Return connectionprovider returns the connectionprovider of the parent class.
*/
Public static connectionprovider newinstance (Java. util. properties Pro) throws
Unknownhostexception, ioexception {
If (provider = NULL ){
Synchronized (object_lock ){
If (provider = NULL ){
Provider = new myconnectionprovider (Pro );
}
}
}
Return provider;
}
/**
* Set system properties to encapsulate the required values by encapsulating the System Properties object.
* Server_ip, server_port, max_size, min_size, and other parameters defined by the parent class
* @ Param pro properties system attributes passed in
*/
Public void setproperties (properties Pro ){
This. Pro = pro;
}
}

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.