Java Singleton locking method

Source: Internet
Author: User

Java Singleton locking method:

ScheduleEngine is a singleton class. In the getinstance method of obtaining an instance, it checks whether it is null twice, which is conducive to concurrent operations of multiple threads.

This improves the efficiency by locking the instance for the first time.

 

Java code
Class ScheduleEngine {

Private static Lock instanceLock = new ReentrantLock ();

Private ScheduleEngine (){
Setproperties;
}

Public static ScheduleEngine getInstance (int temphandlerType ){
If (null = engine ){
InstanceLock. lock ();
Try
{
If (null = engine)
{
HandlerType = temphandlerType;
Engine = new ScheduleEngine (temphandlerType );
}

}
Finally
{
InstanceLock. unlock ();
}
}
Return engine;
}
}
 

The method for initial instantiation of the single-instance c3p0 object is commonly used

 

Java code
Public final class ConnectionManager {
 
Private static ConnectionManager instance;
Private static ComboPooledDataSource CPPS;
 
Private static String c3p0Properties;
 
/**
* Obtain the connection from the database connection pool
* @ Throws Exception
*/
Private ConnectionManager () throws Exception {
Properties p = new Properties ();
C3p0Properties = System. getProperty ("user. dir") +
"/Mom_project_config/database. properties ";
// P. load (this. getClass (). getClassLoader (). getResourceAsStream (c3p0Properties ));
P. load (new BufferedInputStream (new FileInputStream (c3p0Properties )));
// String url = p. getProperty ("url") + p. getProperty ("database ");
String url = p. getProperty ("url") + p. getProperty ("database") + "? UseUnicode = true & characterEncoding = UTF-8 ";
CPPS = new ComboPooledDataSource ();
CPPS. setDriverClass (p. getProperty ("driverclass "));
CPPS. setJdbcUrl (url );
CPPS. setUser (p. getProperty ("user "));
CPPS. setPassword (p. getProperty ("password "));
// The number of connections that c3p0 obtains at the same time when connections in the connection pool are exhausted. Default: 3 acquireIncrement
CPPS. setAcquireIncrement (Integer. valueOf (p
. GetProperty ("acquireincrement ")));
// Defines the number of repeated attempts after a new connection fails to be obtained from the database. Default: 30 acquireRetryAttempts
CPPS. setAcquireRetryAttempts (Integer. valueOf (p
. GetProperty ("acquireretryattempts ")));
// The interval between two connections, in milliseconds. Default: 1000 acquireRetryDelay
CPPS. setAcquireRetryDelay (Integer. valueOf (p
. GetProperty ("acquireretrydelay ")));
// Automatically submit the transaction. When the connection is closed, all uncommitted operations are rolled back by default. Default: false autoCommitOnClose
CPPS. setAutoCommitOnClose (Boolean. valueOf (p
. GetProperty ("autocommitonclose ")));
// When the connection pool is used up, the client calls getConnection () and waits for the time to obtain the new connection. After the timeout, SQLException is thrown,
// If it is set to 0, it will wait for an indefinite period. Unit: milliseconds. The default value is 0.
CPPS. setCheckoutTimeout (Integer. valueOf (p
. GetProperty ("checkouttimeout ")));
// Check the idle connections in all connection pools every second. The default value is 0, indicating no check. Default: 0 idleConnectionTestPeriod
CPPS. setIdleConnectionTestPeriod (Integer. valueOf (p
. GetProperty ("idleconnectiontestperiod ")));
// Maximum idle time. The connection is dropped if it is not used within 25000 seconds. If it is 0, it will never be discarded. Default: 0 maxIdleTime
CPPS. setMaxIdleTime (Integer. valueOf (p. getProperty ("maxidletime ")));
// Obtain three connections during initialization. The value must be between minPoolSize and maxPoolSize. Default: 3 initialPoolSize
CPPS. setInitialPoolSize (Integer. valueOf (p
. GetProperty ("initialpoolsize ")));
// The minimum number of connections retained in the connection pool.
CPPS. setMinPoolSize (Integer. valueOf (p. getProperty ("minpoolsize ")));
// The maximum number of connections retained in the connection pool. Default: 15 maxPoolSize
CPPS. setMaxPoolSize (Integer. valueOf (p. getProperty ("maxpoolsize ")));
// JDBC standard parameters are used to control the PreparedStatement data loaded in the data source. However, the pre-Cache Statement belongs to a single Connection rather than the entire Connection pool.
// Set this parameter to filter out many factors. If both maxStatements and maxStatementsPerConnection are 0, the cache is disabled. The default value is 0;
CPPS. setMaxStatements (Integer. valueOf (p. getProperty ("maxstatements ")));
// The maximum cache of a single connection in the connection pool is disabled. The default value is 0;
CPPS. setMaxStatementsPerConnection (Integer. valueOf (p
. GetProperty ("maxstatementsperconnection ")));
// C3P0 is an asynchronous operation. Slow JDBC operations can help the process to complete. Extension of these operations can effectively improve performance. Multiple operations can be executed simultaneously through most processes. The default value is 3.
CPPS. setNumHelperThreads (Integer. valueOf (p
. GetProperty ("numhelperthreads ")));
// The maximum number of seconds that the user can wait before modifying system configuration parameters. The default value is 300;
CPPS. setPropertyCycle (Integer. valueOf (p. getProperty ("propertycycle ")));
// If it is set to true, the connection validity will be verified when the connection is obtained. Default: false testConnectionOnCheckin
CPPS. setTestConnectionOnCheckin (Boolean. valueOf (p
. GetProperty ("testconnectiononcheckin ")));
// Because of high performance consumption, use it only when needed.
// If it is set to true, the validity of each connection is verified when it is submitted.
// We recommend that you use idleConnectionTestPeriod or automaticTestTable to improve the connection test performance. Default:
// False testConnectionOnCheckout
CPPS. setTestConnectionOnCheckout (Boolean. valueOf (p
. GetProperty ("testconnectioncheckout ")));
// Failed to obtain the connection will cause all threads waiting for the connection pool to obtain the connection to throw an exception.
// But the data source is still valid, and the next call to getConnection () will continue to try to get the connection.
// If it is set to true, the data source will be declared disconnected and permanently closed after the connection attempt fails. Default: false
// BreakAfterAcquireFailure
CPPS. setBreakAfterAcquireFailure (Boolean. valueOf (p
. GetProperty ("breakafteracquirefailure ")));
 
}
 
/**
* Obtain the ConnectionManager singleton object
* @ Return
*/
Public synchronized static ConnectionManager getInstance (){
If (instance = null ){
Try {
Instance = new ConnectionManager ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
Return instance;
}
 
/**
* Obtain the connection
* @ Return
*/
Public Connection getContection (){
Try {
Return CPPS. getConnection ();
} Catch (SQLException e ){
E. printStackTrace ();
} Www.2cto.com
Return null;
}


Author: tbwshc

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.