2013-12-25 2 views
0

Привет У меня есть Java программа с JDBC, я использовал темы в этом, но я собирающий исключение, как это:Использование ThreadPool в программе

Exception in thread "Thread-1964" java.lang.OutOfMemoryError: Java heap space 

Я думаю, потому что я начинаю нити infinitly и не закрывая также

Так что, я хочу использовать пул потоков, sp, что нить пришла из пула и после выполнения задачи пойдет в пул.

Это мой Java-код:

public class DBTestCases{ 

    Connection localConnection; 
    Connection remoteConnection; 
    Connection localCon; 
    Connection remoteCon; 
    List<Connection> connectionsList; 
    String driver = "com.mysql.jdbc.Driver"; 
    String user = "root"; 
    String password = "root"; 
    String dbName = "myDB"; 
    String connectionUrl1= "jdbc:mysql://11.232.33:3306/"+dbName+"?user="+user+"&password="+password+"&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10"; 
    String connectionUrl2= "jdbc:mysql://localhost:3306/"+dbName+"?user="+user+"&password="+password+"&useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&failOverReadOnly=false&maxReconnects=10"; 

    public List<Connection> createConnection() { 

     try { 
        Class.forName(driver); 
        localCon = DriverManager.getConnection(connectionUrl2); 
        if(localCon != null) 
         System.out.println("connected to remote database at : "+new Date()); 
        remoteCon = DriverManager.getConnection(connectionUrl1); 
        if(remoteCon != null) 
         System.out.println("connected to local database at : "+new Date()); 
        connectionsList = new ArrayList<Connection>(2); 
        connectionsList.add(0 , localCon); 
        connectionsList.add(1 , remoteCon); 
       } catch(ClassNotFoundException cnfe) { 
        cnfe.printStackTrace(); 
        } catch(SQLException sqle) { 
         sqle.printStackTrace(); 
         } 
     return connectionsList; 
    } 

    public void insert(){ 

     Runnable runnable = new Runnable(){ 
     public void run() { 
     PreparedStatement ps1 = null; 
     PreparedStatement ps2 = null; 
     String sql = "insert into user1(name, address, created_date)" + 
           " values('johnsan', 'usa', '2013-08-04')"; 
     if(remoteConnection != null&&localConnection != null) { 
      System.out.println("Database Connection Is Established"); 
      try { 
         ps1 = remoteConnection.prepareStatement(sql); 
         ps2 = localConnection.prepareStatement(sql); 
         int i = ps1.executeUpdate(); 
         int k = ps2.executeUpdate(); 
         if(i > 0) { 
          System.out.println("Data Inserted into remote database table Successfully"); 
         } 
         if(k > 0) { 
          System.out.println("Data Inserted into local database table Successfully"); 
         } 
        } catch (SQLException s) { 
          System.out.println("SQL code does not execute."); 
          s.printStackTrace(); 
         }catch (Exception e) { 
          e.printStackTrace(); 
         } 
      } 
      System.out.println("Inserting values in db"); 
     } 
     }; 
     Thread thread = new Thread(runnable); 
     thread.start(); 
    } 

    public void retrieve(){ 

     Runnable runnable = new Runnable(){ 
     public void run() { 
     try { 
        Statement st1 = localConnection.createStatement(); 
        Statement st2 = remoteConnection.createStatement(); 
        ResultSet res1 = st1.executeQuery("SELECT * FROM user1"); 
        ResultSet res2 = st2.executeQuery("SELECT * FROM user1"); 
        System.out.println("---------------------------Local Database------------------------"); 
        while (res1.next()) { 
         Long i = res1.getLong("userId"); 
         String s1 = res1.getString("name"); 
         String s2 = res1.getString("address"); 
         java.sql.Date d = res1.getDate("created_date"); 
         System.out.println(i + "\t\t" + s1 + "\t\t" + s2 + "\t\t"+ d); 
        } 
        System.out.println("------------------------Remote Database---------------------"); 
        while (res2.next()) { 
         Long i = res2.getLong("userId"); 
         String s1 = res2.getString("name"); 
         String s2 = res2.getString("address"); 
         java.sql.Date d = res2.getDate("created_date"); 
         System.out.println(i + "\t\t" + s1 + "\t\t" + s2 + "\t\t"+ d); 
        } 
     } catch (SQLException s) { 
       System.out.println("SQL code does not execute."); 
       s.printStackTrace(); 
     }catch (Exception e) { 
       e.printStackTrace(); 
     } 
     } 
     }; 
     Thread thread = new Thread(runnable); 
     thread.start(); 
    } 

    public static void main(String[] args) { 
     DBTestCases dbTestCases = new DBTestCases(); 
     List l = dbTestCases.createConnection(); 
     dbTestCases.localConnection = (Connection)l.get(0); 
     dbTestCases.remoteConnection = (Connection)l.get(1); 
     for(;;) { 
      dbTestCases.insert(); 
      dbTestCases.countRows(); 
      dbTestCases.retrieve(); 
     } 
    } 
} 

Пожалуйста, скажите мне, как я должен изменить эту программу с помощью резьбы pool..so, что я не получу это исключение

Thankyou заранее

+0

http://bobah.net/d4d/source-code/misc/thread-pool-executor-example-j2ee, в большинстве случаев вам нужно иметь подключение JDBC пул, чтобы убедиться, что потоки не блокируются в сокете JDBC. Ваша программа выглядит как попытка DoS как локальных, так и удаленных систем. – bobah

+0

Да, я хочу, чтобы моя программа одновременно открывала и удаляла удаленные и локальные базы данных. – joee

+0

DoS - это отказ в обслуживании - он наполнит обе службы командами. –

ответ

Смежные вопросы