package net.nanopool;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.ConnectionPoolDataSource;
import javax.sql.PooledConnection;

import net.nanopool.cas.CasArray;

public class Connector {
    private final ConnectionPoolDataSource source;
    private final CasArray<Connector> connectors;
    private final int idx;
    private final long timeToLive;
    private PooledConnection connection;
    private long deadTime;
    
    public Connector(ConnectionPoolDataSource source,
            CasArray<Connector> connectors, int idx, long timeToLive) {
        this.source = source;
        this.connectors = connectors;
        this.idx = idx;
        this.timeToLive = timeToLive;
    }
    
    Connector() {
        this(null, null, 0, 0);
    }
    
    public Connection getConnection() throws SQLException {
        long now = System.currentTimeMillis();
        if (deadTime < now) {
            PooledConnection con = connection;
            connection = null;
            con.close();
        }
        if (connection == null) {
            connection = source.getPooledConnection();
            connection.addConnectionEventListener(new ConnectionListener(this));
            deadTime = now + timeToLive;
        }
        return connection.getConnection();
    }
    
    public void returnToPool() {
        Connector ticket = connectors.get(idx);
        connectors.cas(idx, this, ticket);
    }
    
    public void invalidate() {
        connection = null;
    }
}

@@ -912,18 +912,16 @@
 e %3C now)
- %7B
 %0A       
@@ -925,23 +925,17 @@
         
-PooledC
+c
 onnectio
@@ -940,91 +940,31 @@
 ion 
-con = connection;%0A            connection = null;%0A            con.close();%0A        %7D
+= toClosed(connection);
 %0A   
@@ -1433,11 +1433,171 @@
 l;%0A    %7D
+%0A%0A    private PooledConnection toClosed(PooledConnection con) throws SQLException %7B%0A        if (con != null)%0A            con.close();%0A        return null;%0A    %7D
 %0A%7D%0A

Fix NPE.