How to use progress bar in java? - java

I want to show progress in progress bar in java GUI, but the progress don't show anything until the process is done.
this is my try:
public void selectTweet(){
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
conn = Drive
rManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
//menghitung jumlah query pada table tweet
String sql = "SELECT COUNT(*) FROM tweet";
ResultSet rs=stmt.executeQuery(sql);
int row = 0;
while(rs.next()){
row = rs.getInt("COUNT(*)");
}
int initial_number = Integer.parseInt(jTextField4.getText());
for(int i=initial_number;i<row;i++){
System.out.println("tweet ke-"+i);
String sql1 = "SELECT tweet,date,location FROM tweet WHERE tweet_id='"+i+"'";
ResultSet rs2 = stmt.executeQuery(sql1);
while(rs2.next()){
tweet = rs2.getString("tweet");
date = rs2.getString("date");
location = rs2.getString("location");
}
System.out.println("Tweet: " + tweet);
removeStopWords(tweet, i, date, location);
final int currentValue = i;
try{
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
jProgressBar1.setValue(currentValue);
}
});
java.lang.Thread.sleep(100);
}catch (InterruptedException e) {
//JOptionPane.showMessageDialog(frame, e.getMessage());
}
}
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}
what i want to do is remove stopwords in string records from database, there are 5000 records, then i want to use progressbar to show the process, but it's not working. what i missed?, help me please.

You need to process your task in a separate Thread. If you don't, you block the main Swing thread in which the repaint method is called. Plus, I don't see any ProgressBar in your code, you must update its value when a step of the task have been performed.
SwingUtilities.invokeLater(
new Runnable(
public void run() {
for(int i=initial_number;i<row;i++){
System.out.println("tweet ke-"+i);
String sql1 = "SELECT tweet,date,location FROM tweet WHERE tweet_id='"+i+"'";
ResultSet rs2 = stmt.executeQuery(sql1);
while(rs2.next()){
tweet = rs2.getString("tweet");
date = rs2.getString("date");
location = rs2.getString("location");
}
System.out.println("Tweet: " + tweet);
removeStopWords(tweet, i, date, location);
jTextArea1.append(toTextArea);
// the JProgressBar must have been instantiated
// as new JProgressBar(initial_number,row - 1)
jProgressBar1.setValue(i);
}
}));

Using SwingWorker for long running tasks can make things easier.
public void selectTweet()
{
final int initial_number = Integer.parseInt(jTextField4.getText()); // This should be done outside of the worker because you are accessing a UI element's data.
SwingWorker<Void, int[]> worker = new SwingWorker<Void, int[]>()
{
#Override
protected Void doInBackground() throws Exception
{
Connection conn = null;
Statement stmt = null;
try
{
Class.forName( "com.mysql.jdbc.Driver" );
conn = DriverManager.getConnection( DB_URL, USER, PASS );
stmt = conn.createStatement();
String sql = "SELECT COUNT(*) FROM tweet";
ResultSet rs = stmt.executeQuery( sql );
int row = 0;
while( rs.next() )
{
row = rs.getInt( "COUNT(*)" );
}
for( int i = initial_number; i < row; i++ )
{
System.out.println( "tweet ke-" + i );
String sql1 = "SELECT tweet,date,location FROM tweet WHERE tweet_id='" + i + "'";
ResultSet rs2 = stmt.executeQuery( sql1 );
String tweet, date, location;
while( rs2.next() )
{
tweet = rs2.getString( "tweet" );
date = rs2.getString( "date" );
location = rs2.getString( "location" );
}
System.out.println( "Tweet: " + tweet );
removeStopWords( tweet, i, date, location );
publish( new int[]{i,row} );
}
}
catch( SQLException se )
{
//Handle errors for JDBC
se.printStackTrace();
}
catch( Exception e )
{
//Handle errors for Class.forName
e.printStackTrace();
}
finally
{
//finally block used to close resources
try
{
if( stmt != null )
conn.close();
}
catch( SQLException se )
{
}// do nothing
try
{
if( conn != null )
conn.close();
}
catch( SQLException se )
{
se.printStackTrace();
}//end finally try
}//end try
}
#Override
protected void process( List<int[]> chunks ) // Run in the EDT, so no invokeLater needed
{
if( chunks == null || chunks.isEmpty() )
return;
int[] last = chunks.get( chunks.size() - 1 );
jProgressBar1.setMinimum( 0 );
jProgressBar1.setMaximum( last[1] - initial_number );
jProgressBar1.setValue( last[0] - initial_number );
}
#Override
protected void done() // Run in the EDT, so no invokeLater needed
{
jProgressBar1.setValue( jProgressBar1.getMaximum() );
}
};
worker.execute();
}

Related

What is the right way to deal with the PreparedStatement in the Java program flow?

There are two methods in which the PreparedStatement is used.
The first method is called in the second method.
First method:
protected List<String> findResultsByMandantId(Long mandantId) {
List<String> resultIds = new ArrayList<>();
ResultSet rs;
String sql = "SELECT result_id FROM results WHERE mandant_id = ?";
PreparedStatement statement = getPreparedStatement(sql, false);
try {
statement.setLong(1, mandantId);
statement.execute();
rs = statement.getResultSet();
while (rs.next()) {
resultIds.add(rs.getString(1));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
return resultIds;
}
Second method:
protected void findResultLineEntityToDelete(Long mandantId, String title, String context) {
List<String> resultIds = findResultsByMandantId(mandantId);
String [] resultIdsArr = resultIds.toArray(String[]::new);
ResultSet rs;
//String sql = "SELECT * FROM resultline WHERE result_id in (SELECT result_id FROM results WHERE mandant_id =" + mandantId + ")";
String sql = "SELECT * FROM resultline WHERE result_id in (" + String.join(", ", resultIdsArr)+ ")";
PreparedStatement statement = getPreparedStatement(sql, false);
try {
statement.execute();
rs = statement.getResultSet();
while (rs.next()) {
if (rs.getString(3).equals(title) && rs.getString(4).equals(context)) {
System.out.println("Titel: " + rs.getString(3) + " " + "Context: " + rs.getString(4));
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
The class in which both methods are located extends the JDBCBaseManager.
JDBCBaseManager:
private final String url = "jdbc:mysql://localhost:3306/database";
private final String userName = "root";
private final String password = "";
private Connection connection = null;
private PreparedStatement preparedStatement = null;
private int batchSize = 0;
public JDBCBaseManager() {
// Dotenv env = Dotenv.configure().directory("./serverless").load();
// url = env.get("DB_PROD_URL");
// userName = env.get("DB_USER");
// password = env.get("DB_PW");
}
public void getConnection() {
try {
if (connection == null) {
connection = DriverManager.getConnection(url, userName, password);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public PreparedStatement getPreparedStatement(String sql, boolean returnGeneratedKeys) {
try {
if (connection == null) {
getConnection();
}
if (preparedStatement == null) {
if (!returnGeneratedKeys) {
preparedStatement = connection.prepareStatement(sql);
} else {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(false);
}
}
return preparedStatement;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void closeConnection() {
try {
if (connection != null && !connection.isClosed()) {
System.out.println("Closing Database Connection");
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void startBatch(int batchSize) throws SQLException {
connection.setAutoCommit(false);
setBatchSize(batchSize);
}
public void commit() {
try {
if (connection != null && !connection.isClosed()) {
connection.commit();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public int getBatchSize() {
return batchSize;
}
public void setBatchSize(int batchSize) {
this.batchSize = batchSize;
}
The ResultSet in the second method still contains the results from the first method.
I already tried to close the connection and open it again before the second method is executed, but then I get the errors:
java.sql.SQLException: No operations allowed after statement closed.
java.sql.SQLNonTransientConnectionException: No operations allowed
after connection closed.
Can you tell me how to deal with the statement correctly in this case? Is my BaseManager incorrectly structured?
Here lies the error
public JDBCBaseManager() {
private PreparedStatement preparedStatement = null;
public PreparedStatement getPreparedStatement(String sql, boolean returnGeneratedKeys) {
try {
......
if (preparedStatement == null) {
if (!returnGeneratedKeys) {
preparedStatement = connection.prepareStatement(sql);
} else {
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
connection.setAutoCommit(false);
}
}
return preparedStatement;
You build the prepare statement only the first time the method getPreparedStatement is called because only the first time the field preparedStatement is null. Every next time you call the method getPreparedStatement you receive the previous preparedStatement from the previous SQL and not the new one.
Remove the check for if (preparedStatement == null) {
You need to build a new preparedStatement every time you want to execute a new SQL.

Using two combobox to set conditions for a search in a database and displaying in jtable

I need to display the details of students in a particular stream of a schoolclass in Jtable from a database containing all the names of students in the school. I have two jComboboxes, on to select which class and the other to select the stream. I am asking for a way to define these two conditions in order to display all the students in a particular stream in a jtable. I apologize in advance if my code is messy.
public Classes() {
initComponents();
show_student();
}
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms", "root", "");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return con;
}
public ArrayList<Individualclass> studentList(String ValToSearch) {
ArrayList<Individualclass> list = new
ArrayList<Individualclass>();
Statement st;
ResultSet rs;
try {
Connection con=getConnection();
st = con.createStatement();
String searchQuery = "SELECT * FROM `students` WHERE CONCAT(`firstName`, `surname`, `otherNames`, `regNo`) LIKE '%"+ValToSearch+"%'";
rs = st.executeQuery("searchQuery ");
Individualclass ic;
while(rs.next()) {
ic = new Individualclass(
rs.getString("firstName"),
rs.getString("surname"),
rs.getString("otherNames"),
rs.getInt("regNo")
);
list.add(ic);
}
} catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return list;
}
public void findStudents() {
}
private void sClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sClassActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where sClass=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String) sClass.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_sClassActionPerformed
private void streamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_streamActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where stream=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String)stream.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_streamActionPerformed
public void show_student() {
ArrayList<Individualclass> list = new ArrayList<Individualclass>();
DefaultTableModel model = (DefaultTableModel)jTable_Display_Student.getModel();
Object [] row = new Object[13];
for(int i = 0; i < list.size(); i++) {
row[0] = list.get(i).getFirstName();
row[1] = list.get(i).getsurname();
row[2] = list.get(i).getOtherNames();
row[3] = list.get(i).getregNo();
model.addRow(row);
}
}

Null result statement from other class

The result set that I'm trying to retrieve from another class returns null, even though the query works.I'm trying to initialize my object based on the records kept in databases,which means if there is initially a record in sqlite,I retrieve the one with latest date.Else,I try to retrieve the earliest one from mysql database. The code that is supposed to retrieve result set from mysql database is like this:
public ResultSet lowestDate() throws SQLException {
ResultSet rs1 = null;
String resultQuery = "SELECT * FROM alarm ORDER BY `timestamp` ASC LIMIT 1";
rs1 = stmt.executeQuery(resultQuery);
return rs1;
}
Statement is initialized globally.And I call this in another class like this:
public void setLastAlarm() throws SQLException, ParseException {
String liteQuery = "SELECT * FROM alarm_entries ORDER BY date(`timestamp`) DESC LIMIT 1";
conn.connectLite();
Connection getCon = conn.getLiteConnection();
try {
stmt = getCon.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
try {
rs = stmt.executeQuery(liteQuery);
if (rs.next()) {
//while (rs.next()) {
nuDate = rs.getString("timestamp");
newDate = format.parse(nuDate);
lastAlarm.setBacklogId(rs.getBytes("backlog_id"));
lastAlarm.setTimestamp(newDate);
//}
}
else{
rsq=mysqlConnection.lowestDate();
lastAlarm.setTimestamp(format.parse(rsq.getString("timestamp")));
lastAlarm.setBacklogId(rsq.getBytes("backlog_id"));
}
}catch (Exception e){
e.printStackTrace();
}
}
public void run() {
try {
setLastAlarm();
You never call ResultSet#next() on the result set being returned from the lowestDate() helper method. Hence, the cursor is never being advanced to the first (and only) record in the result set. But I think it is a bad idea to factor your JDBC code in this way. Instead, just inline your two queries like this:
try {
rs = stmt.executeQuery(liteQuery);
if (rs.next()) {
nuDate = rs.getString("timestamp");
newDate = format.parse(nuDate);
lastAlarm.setBacklogId(rs.getBytes("backlog_id"));
lastAlarm.setTimestamp(newDate);
}
else {
String resultQuery = "SELECT * FROM alarm ORDER BY timestamp LIMIT 1";
rs = stmt.executeQuery(resultQuery);
if (rs.next()) {
String ts = rs.getString("timestamp");
lastAlarm.setTimestamp(format.parse(ts));
lastAlarm.setBacklogId(rs.getBytes("backlog_id"));
}
}
} catch (Exception e){
e.printStackTrace();
}

Using profiling tool to find the exact reason for outOfMemoryError in the java code

Hi i have a java program for accessing remote as well as local databases at the same time using JDBC.
But i am getting this exception:
->Exception in thread "Thread-1964" java.lang.OutOfMemoryError: Java heap space
Now i wanted to use any profiling tool through whic i can get exact reason for this exception in my code.
This is my java program
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();
}
}
}
PLease can anybody help me which is the best tool to use and how i have to use it,and any links for this.i am using linux operating system.
I think i am starting a new thread for each call of method can anybody suggest how to close thread before starting it again or use thred pool..
Thankyou in advance.
The same problem has happened to me once. The problem is your java reserved heap memory. This heap memory is configurable through one of the java config files; both it's minimum and maximum amount.
There are a lots of profilers.
I have been using Visual VM for a while and that's useful for me, at least. It's easy to use and pretty powerful tool as well.
Here's the link:
http://visualvm.java.net
Not sure which IDE you are using. But there's nothing do do with OutOfMemoryError which mean that it's a RuntimeException.
A little bit of offtopic (because I'm not going to suggest you a profiler), but the problem, I think, comes from these lines
ps1 = remoteConnection.prepareStatement(sql);
ps2 = localConnection.prepareStatement(sql);
int i = ps1.executeUpdate();
int k = ps2.executeUpdate();
and
Statement st1 = localConnection.createStatement();
Statement st2 = remoteConnection.createStatement();
ResultSet res1 = st1.executeQuery("SELECT * FROM user1");
ResultSet res2 = st2.executeQuery("SELECT * FROM user1");
After you create PreparedStatement and use it, you should close it. Either you should use close() method when you don't need it anymore or use try-with-resources (it use close() automatically). Java Tutorial on statements and on try-with-resources. Also consider reading this and this topics.
A would rewrite your code something like this (didn't actually tried it, but it compiles and it supposed to eliminate problems with memory leaks):
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();
} finally {
if (ps1 != null) {
try {
ps1.close();
} catch (SQLException ex) {
System.out.println("Cannot close ps1 statement.");
}
}
if (ps2 != null) {
try {
ps2.close();
} catch (SQLException ex) {
System.out.println("Cannot close ps2 statement.");
}
}
}
}
System.out.println("Inserting values in db");
}
};
Thread thread = new Thread(runnable);
thread.start();
}
public void retrieve(){
Runnable runnable = new Runnable(){
public void run() {
Statement st1 = null;
Statement st2 = null;
ResultSet res1 = null;
ResultSet res2 = null;
try {
st1 = localConnection.createStatement();
st2 = remoteConnection.createStatement();
res1 = st1.executeQuery("SELECT * FROM user1");
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();
} finally {
if (res1 != null) {
try {
res1.close();
} catch (SQLException ex) {
System.out.println("Cannot close res1 result set.");
}
}
if (st1 != null) {
try {
st1.close();
} catch (SQLException ex) {
System.out.println("Cannot close st1 statement.");
ex.printStackTrace();
}
}
if (res2 != null) {
try {
res2.close();
} catch (SQLException ex) {
System.out.println("Cannot close res2 result set.");
}
}
if (st2 != null) {
try {
st2.close();
} catch (SQLException ex) {
System.out.println("Cannot close st2 statement.");
ex.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();
}
}
}
There is also another problem with these statements:
ResultSet res1 = st1.executeQuery("SELECT * FROM user1");
ResultSet res2 = st2.executeQuery("SELECT * FROM user1");
I should never (with very rare exceptions) read entire table without using conditions in WHERE. Also if you need only one column created_date, then you must rewrite it like this:
ResultSet res1 = st1.executeQuery("SELECT created_date FROM user1");
ResultSet res2 = st2.executeQuery("SELECT created_date FROM user1");
But I didn't actually replaced it in a full listing, because it can be just 'quick and dirty' code. :)

Using ThreadPool in the program

Hi i have java program with JDBC,I have used threads in that but i am gettin exception like this:
Exception in thread "Thread-1964" java.lang.OutOfMemoryError: Java heap space
I think because i am starting the threads infinitly and not closing also
so,i want to use thread pool ,sp that thread come from the pool and after performing the task it go pack to the pool.
This is my java code:
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();
}
}
}
Please tell me how i should modify this program to using thread pool..so that i will not get that exception
Thankyou in advance
For a thread pool use an ExecutorService:
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
For example a ThreadPoolExecutor:
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html

Categories