View Javadoc
1   package com.github.davidmoten.rx.jdbc;
2   
3   import java.sql.Connection;
4   import java.sql.SQLException;
5   import java.util.concurrent.atomic.AtomicBoolean;
6   
7   import com.github.davidmoten.rx.jdbc.exceptions.SQLRuntimeException;
8   
9   /**
10   * Provides a singleton {@link Connection} sourced from a
11   * {@link ConnectionProvider} that has autoCommit set to false.
12   */
13  final class ConnectionProviderSingletonManualCommit implements ConnectionProvider {
14  
15      /**
16       * Singleton connection.
17       */
18      private Connection con;
19  
20      /**
21       * Ensures thread-safe setting of con
22       */
23      private AtomicBoolean connectionSet = new AtomicBoolean(false);
24  
25      /**
26       * Provides the singleton connection.
27       */
28      private final ConnectionProvider cp;
29  
30      /**
31       * Constructor.
32       * 
33       * @param cp
34       *            connection provider.
35       */
36      ConnectionProviderSingletonManualCommit(ConnectionProvider cp) {
37          this.cp = cp;
38      }
39  
40      @Override
41      public Connection get() {
42          if (connectionSet.compareAndSet(false, true)) {
43              con = cp.get();
44              try {
45                  con.setAutoCommit(false);
46              } catch (SQLException e) {
47                  throw new SQLRuntimeException(e);
48              }
49          }
50          return con;
51      }
52  
53      @Override
54      public void close() {
55          cp.close();
56      }
57  
58  }