Search code examples
javaconnection-pooling

Pass Connection Pool Object to Method


I need to pass the connection pool object into a ScheduledExecutorService thread but I am having difficulties doing so. I attempted to add final in front of the declaration but that throws the following error... The final local variable connection cannot be assigned. It must be blank and not using a compound assignment

How can properly pass this connection object?

public class AdminManager extends JFrame {

    private JPanel contentPane;
    private JTable tableQueue;
    private JTable tableFilled;

    /**
     * Launch the application.
     * @throws InterruptedException 
     */

    public static void main(String[] args) throws InterruptedException {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    AdminManager frame = new AdminManager();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });

        BoneCP connectionPool = null;
        Connection connection = null;

        try {
            // load the database driver (make sure this is in your classpath!)
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        try {
            // setup the connection pool
            BoneCPConfig config = new BoneCPConfig();
            config.setJdbcUrl("jdbc:mysql://192.0.0.1:3306/db"); // jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb
            config.setUsername("root"); 
            config.setPassword("");
            connectionPool = new BoneCP(config); // setup the connection pool

            connection = connectionPool.getConnection(); // fetch a connection

            if (connection != null){
                System.out.println("Connection successful!");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }        
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable(){
            @Override
            public void run(){
                System.out.println("Working ... ");
                String sql = "SELECT * FROM table;";
                Statement st;
                try {
                    st = connection.createStatement();
                    ResultSet rs = st.executeQuery(sql);
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }


            }
        }, 2000, 1000, TimeUnit.MILLISECONDS);

Solution

  • You could define a dummy reference that is only used inside the executor:

    final Connection conn = connection;
    
    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable(){
            @Override
            public void run(){
                System.out.println("Working ... ");
                String sql = "SELECT * FROM table;";
                Statement st;
                try {
                    st = conn.createStatement();
                    ResultSet rs = st.executeQuery(sql);
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }   
            }
        }, 2000, 1000, TimeUnit.MILLISECONDS);
    

    If the issue cannot be solved this way (can't see the rest of your code), you could define an external task class to hold the code:

    class ThreadTask implements Runnable {
         private Connection connection;
    
         public ThreadTask(Connection c) {
              connection = c;
         }
    
         @Override
         public void run() {
            System.out.println("Working ... ");
            String sql = "SELECT * FROM table;";
            Statement st;
            try {
                st = connection.createStatement();
                ResultSet rs = st.executeQuery(sql);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   
        }
    }
    

    And:

    ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
    exec.scheduleAtFixedRate(new ThreadTask(connection));