Reformatting with new Eclipse formatter settings. Went with a variation of Sun-style, which leads to more compact method bodies, but still white-space to "highlight" class and method declarations.

pull/131/head
Brett Wooldridge 11 years ago
parent 0486c5904e
commit 775cba7db5

@ -82,8 +82,7 @@ public class HikariConfig implements HikariConfigMBean
private IConnectionCustomizer customizer;
private int transactionIsolation;
static
{
static {
JavassistProxyFactory.initialize();
}
@ -133,21 +132,18 @@ public class HikariConfig implements HikariConfigMBean
this();
File propFile = new File(propertyFileName);
if (!propFile.isFile())
{
if (!propFile.isFile()) {
throw new IllegalArgumentException("Property file " + propertyFileName + " was not found.");
}
try
{
try {
FileInputStream fis = new FileInputStream(propFile);
Properties props = new Properties();
props.load(fis);
PropertyBeanSetter.setTargetFromProperties(this, props);
fis.close();
}
catch (IOException io)
{
catch (IOException io) {
throw new RuntimeException("Error loading properties file", io);
}
}
@ -271,16 +267,13 @@ public class HikariConfig implements HikariConfigMBean
@Override
public void setConnectionTimeout(long connectionTimeoutMs)
{
if (connectionTimeoutMs == 0)
{
if (connectionTimeoutMs == 0) {
this.connectionTimeout = Integer.MAX_VALUE;
}
else if (connectionTimeoutMs < 100)
{
else if (connectionTimeoutMs < 100) {
throw new IllegalArgumentException("connectionTimeout cannot be less than 100ms");
}
else
{
else {
this.connectionTimeout = connectionTimeoutMs;
}
}
@ -344,14 +337,12 @@ public class HikariConfig implements HikariConfigMBean
public void setDriverClassName(String driverClassName)
{
try
{
try {
Class<?> driverClass = this.getClass().getClassLoader().loadClass(driverClassName);
driverClass.newInstance();
this.driverClassName = driverClassName;
}
catch (Exception e)
{
catch (Exception e) {
throw new RuntimeException("driverClassName specified class '" + driverClassName + "' could not be loaded", e);
}
}
@ -516,8 +507,7 @@ public class HikariConfig implements HikariConfigMBean
@Override
public void setMaximumPoolSize(int maxPoolSize)
{
if (maxPoolSize < 0)
{
if (maxPoolSize < 0) {
throw new IllegalArgumentException("maxPoolSize cannot be negative");
}
this.maxPoolSize = maxPoolSize;
@ -556,8 +546,7 @@ public class HikariConfig implements HikariConfigMBean
@Override
public void setMinimumIdle(int minIdle)
{
if (minIdle < 0 || minIdle > maxPoolSize)
{
if (minIdle < 0 || minIdle > maxPoolSize) {
throw new IllegalArgumentException("maxPoolSize cannot be negative or greater than maximumPoolSize");
}
this.minIdle = minIdle;
@ -642,63 +631,50 @@ public class HikariConfig implements HikariConfigMBean
validateNumerics();
if (connectionCustomizerClassName != null)
{
try
{
if (connectionCustomizerClassName != null) {
try {
getClass().getClassLoader().loadClass(connectionCustomizerClassName);
}
catch (Exception e)
{
catch (Exception e) {
logger.warn("connectionCustomizationClass specified class '" + connectionCustomizerClassName + "' could not be loaded", e);
connectionCustomizerClassName = null;
}
}
if (driverClassName != null && jdbcUrl == null)
{
if (driverClassName != null && jdbcUrl == null) {
logger.error("when specifying driverClassName, jdbcUrl must also be specified");
throw new IllegalStateException("when specifying driverClassName, jdbcUrl must also be specified");
}
else if (jdbcUrl != null && driverClassName == null)
{
else if (jdbcUrl != null && driverClassName == null) {
logger.error("when specifying jdbcUrl, driverClassName must also be specified");
throw new IllegalStateException("when specifying jdbcUrl, driverClassName must also be specified");
}
else if (driverClassName != null && jdbcUrl != null)
{
else if (driverClassName != null && jdbcUrl != null) {
// OK
}
else if (dataSource == null && dataSourceClassName == null)
{
else if (dataSource == null && dataSourceClassName == null) {
logger.error("one of either dataSource, dataSourceClassName, or jdbcUrl and driverClassName must be specified");
throw new IllegalArgumentException("one of either dataSource or dataSourceClassName must be specified");
}
else if (dataSource != null && dataSourceClassName != null)
{
else if (dataSource != null && dataSourceClassName != null) {
logger.warn("both dataSource and dataSourceClassName are specified, ignoring dataSourceClassName");
}
if (connectionTestQuery != null)
{
if (connectionTestQuery != null) {
isJdbc4connectionTest = false;
}
else if (!isJdbc4connectionTest)
{
else if (!isJdbc4connectionTest) {
logger.error("Either jdbc4ConnectionTest must be enabled or a connectionTestQuery must be specified");
throw new IllegalStateException("Either jdbc4ConnectionTest must be enabled or a connectionTestQuery must be specified");
}
if (transactionIsolationName != null)
{
try
{
if (transactionIsolationName != null) {
try {
Field field = Connection.class.getField(transactionIsolationName);
int level = field.getInt(null);
this.transactionIsolation = level;
}
catch (Exception e)
{
catch (Exception e) {
throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName);
}
}
@ -712,45 +688,37 @@ public class HikariConfig implements HikariConfigMBean
{
Logger logger = LoggerFactory.getLogger(getClass());
if (connectionTimeout == Integer.MAX_VALUE)
{
if (connectionTimeout == Integer.MAX_VALUE) {
logger.warn("No connection wait timeout is set, this might cause an infinite wait");
}
else if (connectionTimeout < TimeUnit.MILLISECONDS.toMillis(250))
{
else if (connectionTimeout < TimeUnit.MILLISECONDS.toMillis(250)) {
logger.warn("connectionTimeout is less than 250ms, did you specify the wrong time unit? Using default instead");
connectionTimeout = CONNECTION_TIMEOUT;
}
if (minIdle < 0)
{
if (minIdle < 0) {
minIdle = maxPoolSize;
}
if (idleTimeout < 0)
{
if (idleTimeout < 0) {
logger.error("idleTimeout cannot be negative.");
throw new IllegalArgumentException("idleTimeout cannot be negative");
}
else if (idleTimeout < TimeUnit.SECONDS.toMillis(30) && idleTimeout != 0)
{
else if (idleTimeout < TimeUnit.SECONDS.toMillis(30) && idleTimeout != 0) {
logger.warn("idleTimeout is less than 30000ms, did you specify the wrong time unit? Using default instead");
idleTimeout = IDLE_TIMEOUT;
}
if (leakDetectionThreshold != 0 && leakDetectionThreshold < TimeUnit.SECONDS.toMillis(10))
{
if (leakDetectionThreshold != 0 && leakDetectionThreshold < TimeUnit.SECONDS.toMillis(10)) {
logger.warn("leakDetectionThreshold is less than 10000ms, did you specify the wrong time unit? Disabling leak detection");
leakDetectionThreshold = 0;
}
if (maxLifetime < 0)
{
if (maxLifetime < 0) {
logger.error("maxLifetime cannot be negative.");
throw new IllegalArgumentException("maxLifetime cannot be negative.");
}
else if (maxLifetime < TimeUnit.SECONDS.toMillis(120) && maxLifetime != 0)
{
else if (maxLifetime < TimeUnit.SECONDS.toMillis(120) && maxLifetime != 0) {
logger.warn("maxLifetime is less than 120000ms, did you specify the wrong time unit? Using default instead.");
maxLifetime = MAX_LIFETIME;
}
@ -760,16 +728,13 @@ public class HikariConfig implements HikariConfigMBean
{
LOGGER.debug("HikariCP pool {} configuration:", poolName);
Set<String> propertyNames = new TreeSet<String>(PropertyBeanSetter.getPropertyNames(HikariConfig.class));
for (String prop : propertyNames)
{
try
{
for (String prop : propertyNames) {
try {
Object value = PropertyBeanSetter.getProperty(prop, this);
prop = (prop + "................................................").substring(0, 32);
LOGGER.debug(prop + (value != null ? value : ""));
}
catch (Exception e)
{
catch (Exception e) {
continue;
}
}
@ -777,17 +742,13 @@ public class HikariConfig implements HikariConfigMBean
void copyState(HikariConfig other)
{
for (Field field : HikariConfig.class.getDeclaredFields())
{
if (!Modifier.isFinal(field.getModifiers()))
{
for (Field field : HikariConfig.class.getDeclaredFields()) {
if (!Modifier.isFinal(field.getModifiers())) {
field.setAccessible(true);
try
{
try {
field.set(other, field.get(this));
}
catch (Exception e)
{
catch (Exception e) {
throw new RuntimeException("Exception copying HikariConfig state: " + e.getMessage(), e);
}
}

@ -83,25 +83,20 @@ public class HikariDataSource extends HikariConfig implements DataSource
@Override
public Connection getConnection() throws SQLException
{
if (isShutdown)
{
if (isShutdown) {
throw new SQLException("Pool has been shutdown");
}
if (fastPathPool != null)
{
if (fastPathPool != null) {
return fastPathPool.getConnection();
}
// See http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java
HikariPool result = pool;
if (result == null)
{
synchronized (this)
{
if (result == null) {
synchronized (this) {
result = pool;
if (result == null)
{
if (result == null) {
validate();
LOGGER.info("HikariCP pool {} is starting.", getPoolName());
pool = result = new HikariPool(this);
@ -117,19 +112,16 @@ public class HikariDataSource extends HikariConfig implements DataSource
@Override
public Connection getConnection(String username, String password) throws SQLException
{
if (isShutdown)
{
if (isShutdown) {
throw new SQLException("Pool has been shutdown");
}
final MultiPoolKey key = new MultiPoolKey(username, password);
HikariPool hikariPool;
synchronized (multiPool)
{
synchronized (multiPool) {
hikariPool = multiPool.get(key);
if (hikariPool == null)
{
if (hikariPool == null) {
hikariPool = new HikariPool(this, username, password);
multiPool.put(key, hikariPool);
}
@ -149,8 +141,7 @@ public class HikariDataSource extends HikariConfig implements DataSource
@Override
public void setLogWriter(PrintWriter out) throws SQLException
{
if (pool.getDataSource() != null)
{
if (pool.getDataSource() != null) {
pool.getDataSource().setLogWriter(out);
}
}
@ -180,8 +171,7 @@ public class HikariDataSource extends HikariConfig implements DataSource
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> iface) throws SQLException
{
if (pool != null && iface.isInstance(pool.getDataSource()))
{
if (pool != null && iface.isInstance(pool.getDataSource())) {
return (T) pool.getDataSource();
}
@ -204,8 +194,7 @@ public class HikariDataSource extends HikariConfig implements DataSource
*/
public void evictConnection(Connection connection)
{
if (!isShutdown && pool != null && connection instanceof IHikariConnectionProxy)
{
if (!isShutdown && pool != null && connection instanceof IHikariConnectionProxy) {
pool.closeConnection((IHikariConnectionProxy) connection);
}
}
@ -223,20 +212,17 @@ public class HikariDataSource extends HikariConfig implements DataSource
*/
public void shutdown()
{
if (isShutdown)
{
if (isShutdown) {
return;
}
isShutdown = true;
if (fastPathPool != null)
{
if (fastPathPool != null) {
shutdownHelper(fastPathPool);
}
for (HikariPool hikariPool : multiPool.values())
{
for (HikariPool hikariPool : multiPool.values()) {
shutdownHelper(hikariPool);
}
}
@ -250,17 +236,14 @@ public class HikariDataSource extends HikariConfig implements DataSource
private void shutdownHelper(HikariPool hPool)
{
try
{
try {
hPool.shutdown();
}
catch (InterruptedException e)
{
catch (InterruptedException e) {
LoggerFactory.getLogger(getClass()).warn("Interrupted during shutdown", e);
}
if (hPool.getDataSource() instanceof DriverDataSource)
{
if (hPool.getDataSource() instanceof DriverDataSource) {
((DriverDataSource) hPool.getDataSource()).shutdown();
}
}
@ -286,20 +269,16 @@ public class HikariDataSource extends HikariConfig implements DataSource
public boolean equals(Object obj)
{
MultiPoolKey otherKey = ((MultiPoolKey) obj);
if (username != null && !username.equals(otherKey.username))
{
if (username != null && !username.equals(otherKey.username)) {
return false;
}
else if (username != otherKey.username)
{
else if (username != otherKey.username) {
return false;
}
else if (password != null && !password.equals(otherKey.password))
{
else if (password != null && !password.equals(otherKey.password)) {
return false;
}
else if (password != otherKey.password)
{
else if (password != otherKey.password) {
return false;
}

@ -41,23 +41,19 @@ public class HikariJNDIFactory implements ObjectFactory
public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception
{
// We only know how to deal with <code>javax.naming.Reference</code> that specify a class name of "javax.sql.DataSource"
if ((obj == null) || !(obj instanceof Reference))
{
if ((obj == null) || !(obj instanceof Reference)) {
return null;
}
Reference ref = (Reference) obj;
if (!"javax.sql.DataSource".equals(ref.getClassName()))
{
if (!"javax.sql.DataSource".equals(ref.getClassName())) {
throw new NamingException(ref.getClassName() + " is not a valid class name/type for this JNDI factory.");
}
Properties properties = new Properties();
for (String propertyName : PropertyBeanSetter.getPropertyNames(HikariConfig.class))
{
for (String propertyName : PropertyBeanSetter.getPropertyNames(HikariConfig.class)) {
RefAddr ra = ref.get(propertyName);
if (ra != null)
{
if (ra != null) {
String propertyValue = ra.getContent().toString();
properties.setProperty(propertyName, propertyValue);
}
@ -68,8 +64,7 @@ public class HikariJNDIFactory implements ObjectFactory
private DataSource createDataSource(Properties properties, Context context)
{
if (properties.getProperty("dataSourceJNDI") != null)
{
if (properties.getProperty("dataSourceJNDI") != null) {
return lookupJndiDataSource(properties, context);
}
@ -80,37 +75,29 @@ public class HikariJNDIFactory implements ObjectFactory
{
DataSource jndiDS = null;
String jndiName = properties.getProperty("dataSourceJNDI");
try
{
if (context != null)
{
try {
if (context != null) {
jndiDS = (DataSource) context.lookup(jndiName);
}
else
{
else {
throw new RuntimeException("dataSourceJNDI property is configued, but local JNDI context is null.");
}
}
catch (NamingException e)
{
catch (NamingException e) {
throw new RuntimeException("The name \"" + jndiName + "\" can not be found in the local context.");
}
if (jndiDS == null)
{
try
{
if (jndiDS == null) {
try {
context = (Context) (new InitialContext());
jndiDS = (DataSource) context.lookup(jndiName);
}
catch (NamingException e)
{
catch (NamingException e) {
throw new RuntimeException("The name \"" + jndiName + "\" can not be found in the InitialContext.");
}
}
if (jndiDS != null)
{
if (jndiDS != null) {
HikariConfig config = new HikariConfig(properties);
config.setDataSource(jndiDS);
return new HikariDataSource(config);

@ -50,11 +50,9 @@ public class HikariConfigurationUtil
copyProperty(AvailableSettings.USER, props, "username", hikariProps);
copyProperty(AvailableSettings.PASS, props, "password", hikariProps);
for (Object keyo : props.keySet())
{
for (Object keyo : props.keySet()) {
String key = (String) keyo;
if (key.startsWith(CONFIG_PREFIX))
{
if (key.startsWith(CONFIG_PREFIX)) {
hikariProps.setProperty(key.substring(CONFIG_PREFIX.length()), (String) props.get(key));
}
}
@ -65,8 +63,7 @@ public class HikariConfigurationUtil
@SuppressWarnings("rawtypes")
private static void copyProperty(String srcKey, Map src, String dstKey, Properties dst)
{
if (src.containsKey(srcKey))
{
if (src.containsKey(srcKey)) {
dst.setProperty(dstKey, (String) src.get(srcKey));
}
}

@ -73,16 +73,14 @@ public class HikariConnectionProvider implements ConnectionProvider, Configurabl
@Override
public void configure(Map props) throws HibernateException
{
try
{
try {
LOGGER.debug("Configuring HikariCP");
this.hcfg = HikariConfigurationUtil.loadConfiguration(props);
this.hds = new HikariDataSource(this.hcfg);
}
catch (Exception e)
{
catch (Exception e) {
throw new HibernateException(e);
}
@ -97,8 +95,7 @@ public class HikariConnectionProvider implements ConnectionProvider, Configurabl
public Connection getConnection() throws SQLException
{
Connection conn = null;
if (this.hds != null)
{
if (this.hds != null) {
conn = this.hds.getConnection();
}
@ -128,12 +125,10 @@ public class HikariConnectionProvider implements ConnectionProvider, Configurabl
@SuppressWarnings("unchecked")
public <T> T unwrap(Class<T> unwrapType)
{
if (isUnwrappableAs(unwrapType))
{
if (isUnwrappableAs(unwrapType)) {
return (T) this;
}
else
{
else {
throw new UnknownUnwrapTypeException(unwrapType);
}
}

@ -57,8 +57,7 @@ public final class CodaHaleMetricsTracker extends MetricsTracker
public void stop()
{
if (innerContext != null)
{
if (innerContext != null) {
innerContext.stop();
}
}

@ -16,7 +16,6 @@
package com.zaxxer.hikari.metrics;
/**
* This class does absolutely nothing.
*

@ -48,24 +48,20 @@ public final class HikariMBeanElf
*/
public static void registerMBeans(HikariConfig configuration, HikariPool pool)
{
try
{
try {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName poolConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + configuration.getPoolName() + ")");
ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + configuration.getPoolName() + ")");
if (!mBeanServer.isRegistered(poolConfigName))
{
if (!mBeanServer.isRegistered(poolConfigName)) {
mBeanServer.registerMBean(configuration, poolConfigName);
mBeanServer.registerMBean(pool, poolName);
}
else
{
else {
LOGGER.error("You cannot use the same HikariConfig for separate pool instances.");
}
}
catch (Exception e)
{
catch (Exception e) {
LOGGER.warn("Unable to register management beans.", e);
}
}
@ -78,24 +74,20 @@ public final class HikariMBeanElf
*/
public static void unregisterMBeans(HikariConfig configuration, HikariPool pool)
{
try
{
try {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName poolConfigName = new ObjectName("com.zaxxer.hikari:type=PoolConfig (" + configuration.getPoolName() + ")");
ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (" + configuration.getPoolName() + ")");
if (mBeanServer.isRegistered(poolConfigName))
{
if (mBeanServer.isRegistered(poolConfigName)) {
mBeanServer.unregisterMBean(poolConfigName);
mBeanServer.unregisterMBean(poolName);
}
else
{
else {
LOGGER.error("No registered MBean for {}.", configuration.getPoolName());
}
}
catch (Exception e)
{
catch (Exception e) {
LOGGER.warn("Unable to unregister management beans.", e);
}
}

@ -128,12 +128,12 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
this.leakDetectionThreshold = configuration.getLeakDetectionThreshold();
this.transactionIsolation = configuration.getTransactionIsolation();
this.isRecordMetrics = configuration.isRecordMetrics();
this.metricsTracker = MetricsFactory.createMetricsTracker((isRecordMetrics ? configuration.getMetricsTrackerClassName() : "com.zaxxer.hikari.metrics.MetricsTracker"), configuration.getPoolName());
this.metricsTracker = MetricsFactory.createMetricsTracker((isRecordMetrics ? configuration.getMetricsTrackerClassName()
: "com.zaxxer.hikari.metrics.MetricsTracker"), configuration.getPoolName());
this.dataSource = initializeDataSource();
if (isRegisteredMbeans)
{
if (isRegisteredMbeans) {
HikariMBeanElf.registerMBeans(configuration, this);
}
@ -158,27 +158,22 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
final MetricsContext context = (isRecordMetrics ? metricsTracker.recordConnectionRequest(start) : MetricsTracker.NO_CONTEXT);
long timeout = connectionTimeout;
try
{
do
{
try {
do {
IHikariConnectionProxy connection = connectionBag.borrow(timeout, TimeUnit.MILLISECONDS);
if (connection == null)
{
if (connection == null) {
break; // We timed out... break and throw exception
}
final long now = System.currentTimeMillis();
connection.unclose(now);
if (now > connection.getExpirationTime() || (now - connection.getLastAccess() > 1000L && !isConnectionAlive(connection, timeout)))
{
if (now > connection.getExpirationTime() || (now - connection.getLastAccess() > 1000L && !isConnectionAlive(connection, timeout))) {
closeConnection(connection); // Throw away the dead connection and try again
timeout -= elapsedTimeMs(start);
continue;
}
else if (leakDetectionThreshold != 0)
{
else if (leakDetectionThreshold != 0) {
connection.captureStack(leakDetectionThreshold, houseKeepingTimer);
}
@ -186,18 +181,16 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
}
while (timeout > 0L);
}
catch (InterruptedException e)
{
catch (InterruptedException e) {
throw new SQLException("Interrupted during connection acquisition", e);
}
finally
{
finally {
context.stop();
}
logPoolState("Timeout failure ");
throw new SQLException(String.format("Timeout of %dms encountered waiting for connection.",
configuration.getConnectionTimeout()), lastConnectionFailure.getAndSet(null));
throw new SQLException(String.format("Timeout of %dms encountered waiting for connection.", configuration.getConnectionTimeout()),
lastConnectionFailure.getAndSet(null));
}
/**
@ -208,13 +201,11 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
*/
public void releaseConnection(final IHikariConnectionProxy connectionProxy, final boolean isBroken)
{
if (isRecordMetrics)
{
if (isRecordMetrics) {
metricsTracker.recordConnectionUsage(elapsedTimeMs(connectionProxy.getLastOpenTime()));
}
if (isBroken || isShutdown)
{
if (isBroken || isShutdown) {
LOGGER.debug("Connection returned to pool {} is broken, or the pool is shutting down. Closing connection.", configuration.getPoolName());
closeConnection(connectionProxy);
return;
@ -231,8 +222,7 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
*/
public void shutdown() throws InterruptedException
{
if (!isShutdown)
{
if (!isShutdown) {
isShutdown = true;
LOGGER.info("HikariCP pool {} is shutting down.", configuration.getPoolName());
@ -241,8 +231,7 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
addConnectionExecutor.shutdownNow();
final long start = System.currentTimeMillis();
do
{
do {
closeIdleConnections();
abortActiveConnections();
}
@ -250,8 +239,7 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
logPoolState("After shutdown ");
if (isRegisteredMbeans)
{
if (isRegisteredMbeans) {
HikariMBeanElf.unregisterMBeans(configuration, this);
}
}
@ -274,21 +262,17 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
*/
public void closeConnection(final IHikariConnectionProxy connectionProxy)
{
try
{
try {
int tc = totalConnections.decrementAndGet();
if (tc < 0)
{
if (tc < 0) {
LOGGER.warn("Internal accounting inconsistency, totalConnections={}", tc, new Exception());
}
connectionProxy.realClose();
}
catch (SQLException e)
{
catch (SQLException e) {
return;
}
finally
{
finally {
connectionBag.remove(connectionProxy);
}
}
@ -307,23 +291,21 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
@Override
public void addBagItem()
{
class AddConnection implements Runnable {
class AddConnection implements Runnable
{
public void run()
{
long sleepBackoff = 200L;
final int maxPoolSize = configuration.getMaximumPoolSize();
final int minIdle = configuration.getMinimumIdle();
while (!isShutdown && totalConnections.get() < maxPoolSize && (minIdle == 0 || getIdleConnections() < minIdle))
{
if (!addConnection())
{
while (!isShutdown && totalConnections.get() < maxPoolSize && (minIdle == 0 || getIdleConnections() < minIdle)) {
if (!addConnection()) {
quietlySleep(sleepBackoff);
sleepBackoff = Math.min(1000L, (long) ((double) sleepBackoff * 1.5));
continue;
}
if (minIdle == 0)
{
if (minIdle == 0) {
break; // This break is here so we only add one connection when there is no min. idle
}
}
@ -369,10 +351,8 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
@Override
public void closeIdleConnections()
{
for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_NOT_IN_USE))
{
if (connectionBag.reserve(connectionProxy))
{
for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_NOT_IN_USE)) {
if (connectionBag.reserve(connectionProxy)) {
closeConnection(connectionProxy);
}
}
@ -388,11 +368,9 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
private boolean addConnection()
{
Connection connection = null;
try
{
try {
// Speculative increment of totalConnections with expectation of success
if (totalConnections.incrementAndGet() > configuration.getMaximumPoolSize() || isShutdown)
{
if (totalConnections.incrementAndGet() > configuration.getMaximumPoolSize() || isShutdown) {
totalConnections.decrementAndGet();
return true;
}
@ -403,15 +381,14 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
executeSqlAutoCommit(connection, configuration.getConnectionInitSql());
IHikariConnectionProxy proxyConnection = ProxyFactory.getProxyConnection(this, connection, configuration.getMaxLifetime(),
transactionIsolation, isAutoCommit, isReadOnly, catalog);
IHikariConnectionProxy proxyConnection = ProxyFactory.getProxyConnection(this, connection, configuration.getMaxLifetime(), transactionIsolation,
isAutoCommit, isReadOnly, catalog);
proxyConnection.resetConnectionState();
connectionBag.add(proxyConnection);
lastConnectionFailure.set(null);
return true;
}
catch (Exception e)
{
catch (Exception e) {
// We failed, so undo speculative increment of totalConnections
totalConnections.decrementAndGet();
@ -431,34 +408,28 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
*/
private boolean isConnectionAlive(final IHikariConnectionProxy connection, long timeoutMs)
{
try
{
try {
final boolean timeoutEnabled = (configuration.getConnectionTimeout() != Integer.MAX_VALUE);
timeoutMs = timeoutEnabled ? Math.max(1000L, timeoutMs) : 0;
if (isJdbc4ConnectionTest)
{
if (isJdbc4ConnectionTest) {
return connection.isValid((int) TimeUnit.MILLISECONDS.toSeconds(timeoutMs));
}
Statement statement = connection.createStatement();
try
{
try {
statement.setQueryTimeout((int) TimeUnit.MILLISECONDS.toSeconds(timeoutMs));
statement.executeQuery(configuration.getConnectionTestQuery());
return true;
}
finally
{
finally {
statement.close();
if (isIsolateInternalQueries && !isAutoCommit)
{
if (isIsolateInternalQueries && !isAutoCommit) {
connection.rollback();
}
}
}
catch (SQLException e)
{
catch (SQLException e) {
LOGGER.warn("Exception during keep alive check, that means the connection must be dead.", e);
return false;
}
@ -469,18 +440,14 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
*/
private void fillPool()
{
if (configuration.isInitializationFailFast())
{
for (int maxIters = configuration.getMinimumIdle(); maxIters > 0; maxIters--)
{
if (!addConnection())
{
if (configuration.isInitializationFailFast()) {
for (int maxIters = configuration.getMinimumIdle(); maxIters > 0; maxIters--) {
if (!addConnection()) {
throw new RuntimeException("Fail-fast during pool initialization", lastConnectionFailure.getAndSet(null));
}
}
}
else if (configuration.getMinimumIdle() > 0)
{
else if (configuration.getMinimumIdle() > 0) {
addBagItem();
}
}
@ -493,31 +460,24 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
private void abortActiveConnections() throws InterruptedException
{
ThreadPoolExecutor assassinExecutor = createThreadPoolExecutor(configuration.getMaximumPoolSize(), "HikariCP connection assassin");
for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_IN_USE))
{
try
{
if (IS_JAVA7)
{
for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_IN_USE)) {
try {
if (IS_JAVA7) {
connectionProxy.abort(assassinExecutor);
continue;
}
connectionProxy.close();
}
catch (SQLException e)
{
catch (SQLException e) {
continue;
}
finally
{
finally {
totalConnections.decrementAndGet();
try
{
try {
connectionBag.remove(connectionProxy);
}
catch (IllegalStateException ise)
{
catch (IllegalStateException ise) {
continue;
}
}
@ -535,14 +495,12 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
private DataSource initializeDataSource()
{
String dsClassName = configuration.getDataSourceClassName();
if (configuration.getDataSource() == null && dsClassName != null)
{
if (configuration.getDataSource() == null && dsClassName != null) {
DataSource dataSource = createInstance(dsClassName, DataSource.class);
PropertyBeanSetter.setTargetFromProperties(dataSource, configuration.getDataSourceProperties());
return dataSource;
}
else if (configuration.getJdbcUrl() != null)
{
else if (configuration.getJdbcUrl() != null) {
return new DriverDataSource(configuration.getJdbcUrl(), configuration.getDataSourceProperties(), username, password);
}
@ -551,8 +509,7 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
private IConnectionCustomizer initializeCustomizer()
{
if (configuration.getConnectionCustomizerClassName() != null)
{
if (configuration.getConnectionCustomizerClassName() != null) {
return createInstance(configuration.getConnectionCustomizerClassName(), IConnectionCustomizer.class);
}
@ -563,8 +520,8 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
{
int total = totalConnections.get();
int idle = getIdleConnections();
LOGGER.debug("{}pool stats {} (total={}, inUse={}, avail={}, waiting={})", (prefix.length > 0 ? prefix[0] : ""),
configuration.getPoolName(), total, total - idle, idle, getThreadsAwaitingConnection());
LOGGER.debug("{}pool stats {} (total={}, inUse={}, avail={}, waiting={})", (prefix.length > 0 ? prefix[0] : ""), configuration.getPoolName(), total,
total - idle, idle, getThreadsAwaitingConnection());
}
/**
@ -583,14 +540,9 @@ public final class HikariPool implements HikariPoolMBean, IBagStateListener
final long now = System.currentTimeMillis();
final long idleTimeout = configuration.getIdleTimeout();
for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_NOT_IN_USE))
{
if (connectionBag.reserve(connectionProxy))
{
if ((idleTimeout > 0L && now > connectionProxy.getLastAccess() + idleTimeout)
||
(now > connectionProxy.getExpirationTime()))
{
for (IHikariConnectionProxy connectionProxy : connectionBag.values(ConcurrentBag.STATE_NOT_IN_USE)) {
if (connectionBag.reserve(connectionProxy)) {
if ((idleTimeout > 0L && now > connectionProxy.getLastAccess() + idleTimeout) || (now > connectionProxy.getExpirationTime())) {
closeConnection(connectionProxy);
continue;
}

@ -69,8 +69,7 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
private final int hashCode;
// static initializer
static
{
static {
SQL_ERRORS = new HashSet<String>();
SQL_ERRORS.add("57P01"); // ADMIN SHUTDOWN
SQL_ERRORS.add("57P02"); // CRASH SHUTDOWN
@ -80,7 +79,8 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
SQL_ERRORS.add("JZ0C1"); // Sybase disconnect error
}
protected ConnectionProxy(HikariPool pool, Connection connection, long maxLifetime, int defaultIsolationLevel, boolean defaultAutoCommit, boolean defaultReadOnly, String defaultCatalog)
protected ConnectionProxy(HikariPool pool, Connection connection, long maxLifetime, int defaultIsolationLevel, boolean defaultAutoCommit,
boolean defaultReadOnly, String defaultCatalog)
{
this.parentPool = pool;
this.delegate = connection;
@ -137,15 +137,13 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final void checkException(SQLException sqle)
{
String sqlState = sqle.getSQLState();
if (sqlState != null)
{
if (sqlState != null) {
forceClose |= sqlState.startsWith("08") | SQL_ERRORS.contains(sqlState);
if (forceClose)
{
LOGGER.warn(String.format("Connection %s (%s) marked as broken because of SQLSTATE(%s), ErrorCode(%d).", delegate.toString(), parentPool.toString(), sqlState, sqle.getErrorCode()), sqle);
if (forceClose) {
LOGGER.warn(String.format("Connection %s (%s) marked as broken because of SQLSTATE(%s), ErrorCode(%d).", delegate.toString(),
parentPool.toString(), sqlState, sqle.getErrorCode()), sqle);
}
else if (sqle.getNextException() instanceof SQLException)
{
else if (sqle.getNextException() instanceof SQLException) {
checkException(sqle.getNextException());
}
}
@ -190,31 +188,26 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
@Override
public final void resetConnectionState() throws SQLException
{
if (!delegate.getAutoCommit())
{
if (!delegate.getAutoCommit()) {
delegate.rollback();
}
if (isReadOnlyDirty)
{
if (isReadOnlyDirty) {
delegate.setReadOnly(defaultReadOnly);
isReadOnlyDirty = false;
}
if (isAutoCommitDirty)
{
if (isAutoCommitDirty) {
delegate.setAutoCommit(defaultAutoCommit);
isAutoCommitDirty = false;
}
if (isTransactionIsolationDirty)
{
if (isTransactionIsolationDirty) {
delegate.setTransactionIsolation(defaultIsolationLevel);
isTransactionIsolationDirty = false;
}
if (isCatalogDirty && defaultCatalog != null)
{
if (isCatalogDirty && defaultCatalog != null) {
delegate.setCatalog(defaultCatalog);
isCatalogDirty = false;
}
@ -237,8 +230,7 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
// If the connection is not closed. If it is closed, it means this is being
// called back as a result of the close() method below in which case we
// will clear the openStatements collection en mass.
if (!isClosed)
{
if (!isClosed) {
openStatements.remove(statement);
}
}
@ -249,8 +241,7 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
protected final void checkClosed() throws SQLException
{
if (isClosed)
{
if (isClosed) {
throw new SQLException("Connection is closed");
}
}
@ -288,29 +279,22 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
@Override
public final void close() throws SQLException
{
if (!isClosed)
{
if (!isClosed) {
isClosed = true;
if (leakTask != null)
{
if (leakTask != null) {
leakTask.cancel();
leakTask = null;
}
try
{
try {
final int size = openStatements.size();
if (size > 0)
{
for (int i = 0; i < size; i++)
{
try
{
if (size > 0) {
for (int i = 0; i < size; i++) {
try {
openStatements.get(i).close();
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
}
}
@ -320,13 +304,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
resetConnectionState();
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
finally
{
finally {
lastAccess = System.currentTimeMillis();
parentPool.releaseConnection(this, forceClose);
}
@ -345,13 +327,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final Statement createStatement() throws SQLException
{
checkClosed();
try
{
try {
Statement proxyStatement = ProxyFactory.getProxyStatement(this, delegate.createStatement());
return trackStatement(proxyStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -362,13 +342,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
{
checkClosed();
try
{
try {
Statement proxyStatement = ProxyFactory.getProxyStatement(this, delegate.createStatement(resultSetType, resultSetConcurrency));
return trackStatement(proxyStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -379,13 +357,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
checkClosed();
try
{
try {
Statement proxyStatement = ProxyFactory.getProxyStatement(this, delegate.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability));
return trackStatement(proxyStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -396,13 +372,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final CallableStatement prepareCall(String sql) throws SQLException
{
checkClosed();
try
{
try {
CallableStatement proxyCallableStatement = ProxyFactory.getProxyCallableStatement(this, delegate.prepareCall(sql));
return trackStatement(proxyCallableStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -413,13 +387,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
checkClosed();
try
{
try {
CallableStatement proxyCallableStatement = ProxyFactory.getProxyCallableStatement(this, delegate.prepareCall(sql, resultSetType, resultSetConcurrency));
return trackStatement(proxyCallableStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -430,13 +402,12 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
checkClosed();
try
{
CallableStatement proxyCallableStatement = ProxyFactory.getProxyCallableStatement(this, delegate.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability));
try {
CallableStatement proxyCallableStatement = ProxyFactory.getProxyCallableStatement(this, delegate.prepareCall(sql, resultSetType, resultSetConcurrency,
resultSetHoldability));
return trackStatement(proxyCallableStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -447,13 +418,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql) throws SQLException
{
checkClosed();
try
{
try {
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql));
return trackStatement(proxyPreparedStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -464,13 +433,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException
{
checkClosed();
try
{
try {
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, autoGeneratedKeys));
return trackStatement(proxyPreparedStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -481,13 +448,12 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
checkClosed();
try
{
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, resultSetType, resultSetConcurrency));
try {
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this,
delegate.prepareStatement(sql, resultSetType, resultSetConcurrency));
return trackStatement(proxyPreparedStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -498,13 +464,13 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
checkClosed();
try
{
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability));
try {
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, resultSetType,
resultSetConcurrency,
resultSetHoldability));
return trackStatement(proxyPreparedStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -515,13 +481,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException
{
checkClosed();
try
{
try {
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, columnIndexes));
return trackStatement(proxyPreparedStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -532,13 +496,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
{
checkClosed();
try
{
try {
PreparedStatement proxyPreparedStatement = ProxyFactory.getProxyPreparedStatement(this, delegate.prepareStatement(sql, columnNames));
return trackStatement(proxyPreparedStatement);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -548,17 +510,14 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
@Override
public final boolean isValid(int timeout) throws SQLException
{
if (isClosed)
{
if (isClosed) {
return false;
}
try
{
try {
return delegate.isValid(timeout);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -569,13 +528,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final void setAutoCommit(boolean autoCommit) throws SQLException
{
checkClosed();
try
{
try {
delegate.setAutoCommit(autoCommit);
isAutoCommitDirty = (autoCommit != defaultAutoCommit);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -586,13 +543,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final void setReadOnly(boolean readOnly) throws SQLException
{
checkClosed();
try
{
try {
delegate.setReadOnly(readOnly);
isReadOnlyDirty = (readOnly != defaultReadOnly);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -603,13 +558,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final void setTransactionIsolation(int level) throws SQLException
{
checkClosed();
try
{
try {
delegate.setTransactionIsolation(level);
isTransactionIsolationDirty = (level != defaultIsolationLevel);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -619,13 +572,11 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
public final void setCatalog(String catalog) throws SQLException
{
checkClosed();
try
{
try {
delegate.setCatalog(catalog);
isCatalogDirty = !catalog.equals(defaultCatalog);
}
catch (SQLException e)
{
catch (SQLException e) {
checkException(e);
throw e;
}
@ -643,8 +594,7 @@ public abstract class ConnectionProxy implements IHikariConnectionProxy
@SuppressWarnings("unchecked")
public final <T> T unwrap(Class<T> iface) throws SQLException
{
if (iface.isInstance(delegate))
{
if (iface.isInstance(delegate)) {
return (T) delegate;
}

@ -47,23 +47,19 @@ public final class JavassistProxyFactory
{
private ClassPool classPool;
static
{
static {
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try
{
try {
Thread.currentThread().setContextClassLoader(JavassistProxyFactory.class.getClassLoader());
JavassistProxyFactory proxyFactoryFactory = new JavassistProxyFactory();
proxyFactoryFactory.modifyProxyFactory();
}
catch (Exception e)
{
catch (Exception e) {
LoggerFactory.getLogger(JavassistProxyFactory.class).error("Fatal exception during proxy generation", e);
throw new RuntimeException(e);
}
finally
{
finally {
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
}
@ -83,8 +79,7 @@ public final class JavassistProxyFactory
classPool.importPackage("java.sql");
classPool.appendClassPath(new LoaderClassPath(this.getClass().getClassLoader()));
try
{
try {
// Connection is special, it has a checkClosed() call at the beginning
String methodBody = "{ checkClosed(); try { return delegate.method($$); } catch (SQLException e) { checkException(e); throw e;} }";
generateProxyClass(Connection.class, ConnectionProxy.class, methodBody);
@ -98,8 +93,7 @@ public final class JavassistProxyFactory
generateProxyClass(PreparedStatement.class, PreparedStatementProxy.class, methodBody);
generateProxyClass(CallableStatement.class, CallableStatementProxy.class, methodBody);
}
catch (Exception e)
{
catch (Exception e) {
throw new RuntimeException(e);
}
}
@ -108,23 +102,18 @@ public final class JavassistProxyFactory
{
String packageName = JavassistProxyFactory.class.getPackage().getName();
CtClass proxyCt = classPool.getCtClass("com.zaxxer.hikari.proxy.ProxyFactory");
for (CtMethod method : proxyCt.getMethods())
{
for (CtMethod method : proxyCt.getMethods()) {
String methodName = method.getName();
if ("getProxyConnection".equals(methodName))
{
if ("getProxyConnection".equals(methodName)) {
method.setBody("{return new " + packageName + ".ConnectionJavassistProxy($$);}");
}
else if ("getProxyStatement".equals(methodName))
{
else if ("getProxyStatement".equals(methodName)) {
method.setBody("{return new " + packageName + ".StatementJavassistProxy($$);}");
}
else if ("getProxyPreparedStatement".equals(methodName))
{
else if ("getProxyPreparedStatement".equals(methodName)) {
method.setBody("{return new " + packageName + ".PreparedStatementJavassistProxy($$);}");
}
else if ("getProxyCallableStatement".equals(methodName))
{
else if ("getProxyCallableStatement".equals(methodName)) {
method.setBody("{return new " + packageName + ".CallableStatementJavassistProxy($$);}");
}
}
@ -146,10 +135,8 @@ public final class JavassistProxyFactory
// Make a set of method signatures we inherit implementation for, so we don't generate delegates for these
Set<String> superSigs = new HashSet<String>();
for (CtMethod method : superClassCt.getMethods())
{
if ((method.getModifiers() & Modifier.ABSTRACT) != Modifier.ABSTRACT)
{
for (CtMethod method : superClassCt.getMethods()) {
if ((method.getModifiers() & Modifier.ABSTRACT) != Modifier.ABSTRACT) {
superSigs.add(method.getName() + method.getSignature());
}
}
@ -158,23 +145,19 @@ public final class JavassistProxyFactory
Set<String> methods = new HashSet<String>();
Set<Class<?>> interfaces = ClassLoaderUtils.getAllInterfaces(primaryInterface);
for (Class<?> intf : interfaces)
{
for (Class<?> intf : interfaces) {
CtClass intfCt = classPool.getCtClass(intf.getName());
targetCt.addInterface(intfCt);
for (CtMethod intfMethod : intfCt.getDeclaredMethods())
{
for (CtMethod intfMethod : intfCt.getDeclaredMethods()) {
final String signature = intfMethod.getName() + intfMethod.getSignature();
// don't generate delegates for methods we override
if (superSigs.contains(signature))
{
if (superSigs.contains(signature)) {
continue;
}
// Ignore already added methods that come from other interfaces
if (methods.contains(signature))
{
if (methods.contains(signature)) {
continue;
}
@ -186,17 +169,14 @@ public final class JavassistProxyFactory
// Generate a method that simply invokes the same method on the delegate
String modifiedBody;
if (isThrowsSqlException(intfMethod))
{
if (isThrowsSqlException(intfMethod)) {
modifiedBody = methodBody.replace("method", method.getName());
}
else
{
else {
modifiedBody = "{ return ((cast) delegate).method($$); }".replace("method", method.getName()).replace("cast", primaryInterface.getName());
}
if (method.getReturnType() == CtClass.voidType)
{
if (method.getReturnType() == CtClass.voidType) {
modifiedBody = modifiedBody.replace("return", "");
}
@ -205,8 +185,7 @@ public final class JavassistProxyFactory
}
}
if (LoggerFactory.getLogger(getClass()).isDebugEnabled())
{
if (LoggerFactory.getLogger(getClass()).isDebugEnabled()) {
targetCt.debugWriteFile(System.getProperty("java.io.tmpdir"));
}
@ -215,18 +194,14 @@ public final class JavassistProxyFactory
private boolean isThrowsSqlException(CtMethod method)
{
try
{
for (CtClass clazz : method.getExceptionTypes())
{
if (clazz.getSimpleName().equals("SQLException"))
{
try {
for (CtClass clazz : method.getExceptionTypes()) {
if (clazz.getSimpleName().equals("SQLException")) {
return true;
}
}
}
catch (NotFoundException e)
{
catch (NotFoundException e) {
// fall thru
}

@ -38,8 +38,7 @@ class LeakTask extends TimerTask
@Override
public void run()
{
if (System.currentTimeMillis() > leakTime)
{
if (System.currentTimeMillis() > leakTime) {
Exception e = new Exception();
e.setStackTrace(stackTrace);
LoggerFactory.getLogger(LeakTask.class).warn("Connection leak detection triggered, stack trace follows", e);
@ -51,8 +50,7 @@ class LeakTask extends TimerTask
public boolean cancel()
{
boolean cancelled = super.cancel();
if (cancelled)
{
if (cancelled) {
stackTrace = null;
}
return cancelled;

@ -40,12 +40,10 @@ public abstract class PreparedStatementProxy extends StatementProxy implements P
@Override
public final ResultSet executeQuery() throws SQLException
{
try
{
try {
return ((PreparedStatement) delegate).executeQuery();
}
catch (SQLException e)
{
catch (SQLException e) {
connection.checkException(e);
throw e;
}

@ -48,7 +48,8 @@ public final class ProxyFactory
* @param defaultCatalog the default catalog of the underlying {@link Connection}
* @return a proxy that wraps the specified {@link Connection}
*/
public static IHikariConnectionProxy getProxyConnection(HikariPool pool, Connection connection, long maxLifeTime, int defaultIsolationLevel, boolean defaultAutoCommit, boolean defaultIReadOnly, String defaultCatalog)
public static IHikariConnectionProxy getProxyConnection(HikariPool pool, Connection connection, long maxLifeTime, int defaultIsolationLevel,
boolean defaultAutoCommit, boolean defaultIReadOnly, String defaultCatalog)
{
// Body is injected by JavassistProxyFactory
return null;

@ -52,20 +52,17 @@ public abstract class StatementProxy implements Statement
@Override
public final void close() throws SQLException
{
if (isClosed)
{
if (isClosed) {
return;
}
isClosed = true;
connection.untrackStatement(this);
try
{
try {
delegate.close();
}
catch (SQLException e)
{
catch (SQLException e) {
connection.checkException(e);
throw e;
}
@ -75,12 +72,10 @@ public abstract class StatementProxy implements Statement
@Override
public final ResultSet executeQuery(String sql) throws SQLException
{
try
{
try {
return delegate.executeQuery(sql);
}
catch (SQLException e)
{
catch (SQLException e) {
connection.checkException(e);
throw e;
}
@ -90,12 +85,10 @@ public abstract class StatementProxy implements Statement
@Override
public final ResultSet getResultSet() throws SQLException
{
try
{
try {
return delegate.getResultSet();
}
catch (SQLException e)
{
catch (SQLException e) {
connection.checkException(e);
throw e;
}
@ -105,12 +98,10 @@ public abstract class StatementProxy implements Statement
@Override
public final ResultSet getGeneratedKeys() throws SQLException
{
try
{
try {
return delegate.getGeneratedKeys();
}
catch (SQLException e)
{
catch (SQLException e) {
connection.checkException(e);
throw e;
}
@ -127,8 +118,7 @@ public abstract class StatementProxy implements Statement
@SuppressWarnings("unchecked")
public final <T> T unwrap(Class<T> iface) throws SQLException
{
if (iface.isInstance(delegate))
{
if (iface.isInstance(delegate)) {
return (T) delegate;
}

@ -33,8 +33,7 @@ public final class ClassLoaderUtils
public static ClassLoader getClassLoader()
{
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null)
{
if (cl != null) {
return new CascadingClassLoader(cl);
}
return ClassLoaderUtils.class.getClassLoader();
@ -43,8 +42,7 @@ public final class ClassLoaderUtils
public static Class<?> loadClass(String className) throws ClassNotFoundException
{
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl != null)
{
if (cl != null) {
return new CascadingClassLoader(cl).loadClass(className);
}
@ -54,21 +52,17 @@ public final class ClassLoaderUtils
public static Set<Class<?>> getAllInterfaces(Class<?> clazz)
{
Set<Class<?>> interfaces = new HashSet<Class<?>>();
for (Class<?> intf : Arrays.asList(clazz.getInterfaces()))
{
if (intf.getInterfaces().length > 0)
{
for (Class<?> intf : Arrays.asList(clazz.getInterfaces())) {
if (intf.getInterfaces().length > 0) {
interfaces.addAll(getAllInterfaces(intf));
}
interfaces.add(intf);
}
if (clazz.getSuperclass() != null)
{
if (clazz.getSuperclass() != null) {
interfaces.addAll(getAllInterfaces(clazz.getSuperclass()));
}
if (clazz.isInterface())
{
if (clazz.isInterface()) {
interfaces.add(clazz);
}
@ -87,12 +81,10 @@ public final class ClassLoaderUtils
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException
{
try
{
try {
return contextLoader.loadClass(name);
}
catch (ClassNotFoundException cnfe)
{
catch (ClassNotFoundException cnfe) {
return CascadingClassLoader.class.getClassLoader().loadClass(name);
}
}

@ -101,19 +101,15 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
{
// Try the thread-local list first
FastList<WeakReference<T>> list = threadList.get();
if (list == null)
{
if (list == null) {
list = new FastList<WeakReference<T>>(WeakReference.class);
threadList.set(list);
}
else
{
for (int i = list.size() - 1; i >= 0; i--)
{
else {
for (int i = list.size() - 1; i >= 0; i--) {
final WeakReference<T> reference = list.removeLast();
final T element = reference.get();
if (element != null && element.compareAndSetState(STATE_NOT_IN_USE, STATE_IN_USE))
{
if (element != null && element.compareAndSetState(STATE_NOT_IN_USE, STATE_IN_USE)) {
return element;
}
}
@ -123,23 +119,21 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
timeout = timeUnit.toNanos(timeout);
do {
final long startScan = System.nanoTime();
for (T reference : sharedList)
{
if (reference.compareAndSetState(STATE_NOT_IN_USE, STATE_IN_USE))
{
for (T reference : sharedList) {
if (reference.compareAndSetState(STATE_NOT_IN_USE, STATE_IN_USE)) {
return reference;
}
}
if (listener != null)
{
if (listener != null) {
listener.addBagItem();
}
synchronizer.tryAcquireSharedNanos(startScan, timeout);
timeout -= (System.nanoTime() - startScan);
} while (timeout > 0);
}
while (timeout > 0);
return null;
}
@ -155,16 +149,13 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
*/
public void requite(final T value)
{
if (value == null)
{
if (value == null) {
throw new NullPointerException("Cannot return a null value to the bag");
}
if (value.compareAndSetState(STATE_IN_USE, STATE_NOT_IN_USE))
{
if (value.compareAndSetState(STATE_IN_USE, STATE_NOT_IN_USE)) {
FastList<WeakReference<T>> list = threadList.get();
if (list == null)
{
if (list == null) {
list = new FastList<WeakReference<T>>(WeakReference.class);
threadList.set(list);
}
@ -172,8 +163,7 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
list.add(new WeakReference<T>(value));
synchronizer.releaseShared(System.nanoTime());
}
else
{
else {
throw new IllegalStateException("Value was returned to the bag that was not borrowed: ");
}
}
@ -199,15 +189,12 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
*/
public void remove(T value)
{
if (value.compareAndSetState(STATE_IN_USE, STATE_REMOVED) || value.compareAndSetState(STATE_RESERVED, STATE_REMOVED))
{
if (!sharedList.remove(value))
{
if (value.compareAndSetState(STATE_IN_USE, STATE_REMOVED) || value.compareAndSetState(STATE_RESERVED, STATE_REMOVED)) {
if (!sharedList.remove(value)) {
throw new IllegalStateException("Attempt to remove an object from the bag that does not exist");
}
}
else
{
else {
throw new IllegalStateException("Attempt to remove an object from the bag that was not borrowed or reserved");
}
}
@ -224,12 +211,9 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
public List<T> values(int state)
{
ArrayList<T> list = new ArrayList<T>(sharedList.size());
if (state == STATE_IN_USE || state == STATE_NOT_IN_USE)
{
for (T reference : sharedList)
{
if (reference.getState() == state)
{
if (state == STATE_IN_USE || state == STATE_NOT_IN_USE) {
for (T reference : sharedList) {
if (reference.getState() == state) {
list.add(reference);
}
}
@ -263,8 +247,7 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
public void unreserve(T value)
{
final long checkInTime = System.nanoTime();
if (!value.compareAndSetState(STATE_RESERVED, STATE_NOT_IN_USE))
{
if (!value.compareAndSetState(STATE_RESERVED, STATE_NOT_IN_USE)) {
throw new IllegalStateException("Attempt to relinquish an object to the bag that was not reserved");
}
@ -296,10 +279,8 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
public int getCount(int state)
{
int count = 0;
for (T reference : sharedList)
{
if (reference.getState() == state)
{
for (T reference : sharedList) {
if (reference.getState() == state) {
count++;
}
}
@ -324,15 +305,12 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
private static final long serialVersionUID = 104753538004341218L;
private static final boolean JAVA7;
static
{
static {
boolean b = false;
try
{
try {
b = AbstractQueuedLongSynchronizer.class.getMethod("hasQueuedPredecessors", new Class<?>[0]) != null;
}
catch (Exception e)
{
catch (Exception e) {
}
JAVA7 = b;
@ -355,8 +333,7 @@ public class ConcurrentBag<T extends com.zaxxer.hikari.util.ConcurrentBag.IBagMa
private boolean java67hasQueuedPredecessors()
{
if (JAVA7)
{
if (JAVA7) {
return hasQueuedPredecessors();
}

@ -33,26 +33,21 @@ public final class DriverDataSource implements DataSource
public DriverDataSource(String jdbcUrl, Properties properties, String username, String password)
{
try
{
try {
this.jdbcUrl = jdbcUrl;
this.driverProperties = new Properties(properties);
if (username != null)
{
if (username != null) {
driverProperties.put("user", driverProperties.getProperty("user", username));
}
if (password != null)
{
if (password != null) {
driverProperties.put("password", driverProperties.getProperty("password", password));
}
if (DriverManager.getDriver(jdbcUrl) == null)
{
if (DriverManager.getDriver(jdbcUrl) == null) {
throw new IllegalArgumentException("DriverManager was unable to load driver for URL " + jdbcUrl);
}
}
catch (SQLException e)
{
catch (SQLException e) {
throw new RuntimeException("Unable to get driver for JDBC URL " + jdbcUrl);
}
}

@ -18,7 +18,6 @@ package com.zaxxer.hikari.util;
import java.lang.reflect.Array;
/**
* Fast list without range checking.
*
@ -57,12 +56,10 @@ public final class FastList<T>
*/
public void add(T element)
{
try
{
try {
elementData[size++] = element;
}
catch (ArrayIndexOutOfBoundsException e)
{
catch (ArrayIndexOutOfBoundsException e) {
// overflow-conscious code
final int oldCapacity = elementData.length;
final int newCapacity = oldCapacity << 1;
@ -108,13 +105,10 @@ public final class FastList<T>
*/
public void remove(T element)
{
for (int index = size - 1; index >= 0; index--)
{
if (element == elementData[index])
{
for (int index = size - 1; index >= 0; index--) {
if (element == elementData[index]) {
final int numMoved = size - index - 1;
if (numMoved > 0)
{
if (numMoved > 0) {
System.arraycopy(elementData, index + 1, elementData, index, numMoved);
}
elementData[--size] = null;
@ -128,15 +122,13 @@ public final class FastList<T>
*/
public void clear()
{
for (int i = 0; i < size; i++)
{
for (int i = 0; i < size; i++) {
elementData[i] = null;
}
size = 0;
}
/**
* Get the current number of elements in the FastList.
*

@ -14,15 +14,12 @@ public final class PoolUtilities
{
public static final boolean IS_JAVA7;
static
{
static {
boolean b = false;
try
{
try {
b = AbstractQueuedLongSynchronizer.class.getMethod("hasQueuedPredecessors", new Class<?>[0]) != null;
}
catch (Exception e)
{
catch (Exception e) {
}
IS_JAVA7 = b;
@ -30,14 +27,11 @@ public final class PoolUtilities
public static void quietlyCloseConnection(Connection connection)
{
if (connection != null)
{
try
{
if (connection != null) {
try {
connection.close();
}
catch (SQLException e)
{
catch (SQLException e) {
return;
}
}
@ -63,16 +57,13 @@ public final class PoolUtilities
*/
public static void executeSqlAutoCommit(Connection connection, String sql) throws SQLException
{
if (sql != null)
{
if (sql != null) {
connection.setAutoCommit(true);
Statement statement = connection.createStatement();
try
{
try {
statement.execute(sql);
}
finally
{
finally {
statement.close();
}
}
@ -80,12 +71,10 @@ public final class PoolUtilities
public static void quietlySleep(long millis)
{
try
{
try {
Thread.sleep(millis);
}
catch (InterruptedException e)
{
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@ -93,31 +82,26 @@ public final class PoolUtilities
@SuppressWarnings("unchecked")
public static <T> T createInstance(String className, Class<T> clazz, Object... args)
{
if (className == null)
{
if (className == null) {
return null;
}
try
{
try {
Class<?> loaded = PoolUtilities.class.getClassLoader().loadClass(className);
Class<?>[] argClasses = new Class<?>[args.length];
for (int i = 0; i < args.length; i++)
{
for (int i = 0; i < args.length; i++) {
argClasses[i] = args[i].getClass();
}
if (args.length > 0)
{
if (args.length > 0) {
Constructor<?> constructor = loaded.getConstructor(argClasses);
return (T) constructor.newInstance(args);
}
return (T) loaded.newInstance();
}
catch (Exception e)
{
catch (Exception e) {
throw new RuntimeException(e);
}
}
@ -135,7 +119,8 @@ public final class PoolUtilities
int processors = Math.max(1, Runtime.getRuntime().availableProcessors() / 2);
LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(queueSize);
ThreadPoolExecutor executor = new ThreadPoolExecutor(processors, processors, 2, TimeUnit.SECONDS, queue, threadFactory, new ThreadPoolExecutor.DiscardPolicy());
ThreadPoolExecutor executor = new ThreadPoolExecutor(processors, processors, 2, TimeUnit.SECONDS, queue, threadFactory,
new ThreadPoolExecutor.DiscardPolicy());
executor.allowCoreThreadTimeOut(true);
return executor;
}

@ -42,23 +42,19 @@ public final class PropertyBeanSetter
public static void setTargetFromProperties(Object target, Properties properties)
{
if (target == null || properties == null)
{
if (target == null || properties == null) {
return;
}
for (Entry<Object, Object> propEntry : properties.entrySet())
{
for (Entry<Object, Object> propEntry : properties.entrySet()) {
String propName = propEntry.getKey().toString();
Object propValue = propEntry.getValue();
if (target instanceof HikariConfig && propName.startsWith("dataSource."))
{
if (target instanceof HikariConfig && propName.startsWith("dataSource.")) {
HikariConfig config = (HikariConfig) target;
config.addDataSourceProperty(propName.substring("dataSource.".length()), propValue);
}
else
{
else {
setProperty(target, propName, propValue);
}
}
@ -73,43 +69,35 @@ public final class PropertyBeanSetter
public static Set<String> getPropertyNames(Class<?> targetClass)
{
HashSet<String> set = new HashSet<String>();
try
{
try {
BeanInfo info = Introspector.getBeanInfo(targetClass);
for (PropertyDescriptor descr : info.getPropertyDescriptors())
{
if (!"class".equals(descr.getName()))
{
for (PropertyDescriptor descr : info.getPropertyDescriptors()) {
if (!"class".equals(descr.getName())) {
set.add(descr.getName());
}
}
return set;
}
catch (IntrospectionException e)
{
catch (IntrospectionException e) {
throw new RuntimeException(e);
}
}
public static Object getProperty(String propName, Object target)
{
try
{
try {
String capitalized = "get" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
Method method = target.getClass().getMethod(capitalized);
return method.invoke(target);
}
catch (Exception e)
{
try
{
catch (Exception e) {
try {
String capitalized = "is" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
Method method = target.getClass().getMethod(capitalized);
return method.invoke(target);
}
catch (Exception e2)
{
catch (Exception e2) {
return null;
}
}
@ -119,51 +107,40 @@ public final class PropertyBeanSetter
{
String capitalized = "set" + propName.substring(0, 1).toUpperCase() + propName.substring(1);
PropertyDescriptor propertyDescriptor;
try
{
try {
propertyDescriptor = new PropertyDescriptor(propName, target.getClass(), null, capitalized);
}
catch (IntrospectionException e)
{
catch (IntrospectionException e) {
capitalized = "set" + propName.toUpperCase();
try
{
try {
propertyDescriptor = new PropertyDescriptor(propName, target.getClass(), null, capitalized);
}
catch (IntrospectionException e1)
{
catch (IntrospectionException e1) {
LOGGER.error("Property {} is does not exist on target class {}", propName, target.getClass());
throw new RuntimeException(e);
}
}
try
{
try {
Method writeMethod = propertyDescriptor.getWriteMethod();
Class<?> paramClass = writeMethod.getParameterTypes()[0];
if (paramClass == int.class)
{
if (paramClass == int.class) {
writeMethod.invoke(target, Integer.parseInt(propValue.toString()));
}
else if (paramClass == long.class)
{
else if (paramClass == long.class) {
writeMethod.invoke(target, Long.parseLong(propValue.toString()));
}
else if (paramClass == boolean.class)
{
else if (paramClass == boolean.class) {
writeMethod.invoke(target, Boolean.parseBoolean(propValue.toString()));
}
else if (paramClass == String.class)
{
else if (paramClass == String.class) {
writeMethod.invoke(target, propValue.toString());
}
else
{
else {
writeMethod.invoke(target, propValue);
}
}
catch (Exception e)
{
catch (Exception e) {
LOGGER.error("Exception setting property {} on target class {}", propName, target.getClass(), e);
throw new RuntimeException(e);
}

Loading…
Cancel
Save