1

I have a problem with a RESTful Web Service, I have a client in php that call a RESTful Service in Java. In my RESTful Service I have a Post method, which executes an update query to modify all rows in a table with 10000 records . I want to use threads to do this. Is it possible to do that?. Please help me I'm a kind of new in Java. Thanks.

OK I'm doing this in my service layer:

for(int i = 0; i < 10; i++)
{
    startRow = i*1000;
    finalRow = i*1000 + 1000;
    Runnable process = new ProcessRecords(startRow , finalRow);
    executor.execute(process);                    
}

// Wait until all threads are finish
while (!executor.isTerminated()) {

}
System.out.println("\n All threads finished");

And I'm calling this class (ProcessRecords) to execute the update:

public ProcessRecords (int start, int final)
{
    startRow = start;
    finalRow = final;
}

@Override
public void run(){

    try {

        ConsultUniversity consult = new ConsultUniversity ();
        consult.averangeGrade(startRow, finalRow);

    } catch (Exception ex) {
        Logger.getLogger(Procesos.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Then in my Data Layer I'm doing this inside of my method "averangeGrade":

 try {
        conn = UniversityConection();//This is my conection

        query = "SELECT * FROM grades LIMIT " + filaInicial + "," + filaFinal;            
        prepStatement = conn.prepareStatement(query);

        rs = prepStatement.executeQuery(query);  

        rsmd = rs.getMetaData();

        while(rs.next())
        {
            averange = (rs.getInt("nFirGrd") + rs.getInt("nSecGrd") + 
                               rs.getInt("nThrGrd"))/3; //the averange of three grades

            query = "UPDATE grades SET nFinGrd = ? WHERE cCodAlu = ?";

            prepStatement = conn.prepareStatement(query);
            prepStatement.setInt(1, averange);
            prepStatement.setString(2, rs.getString("cCodAlu"));

            prepStatement.executeUpdate();

            System.out.println("Record " + rs.getString("cCodAlu") + 
                                       " modified");
        }               

        conn.close(); //close connection    

    }

Then when I execute my client, my service does the update for the top rows, like 50 rows, then returns the message, like if all processes were finished, and I don't know why. I think is not waiting until all threads are finished, but there is code for that, then why is this happening?. Please help me. Thank you.

5
  • Could you be more specific: (1) What exactly do you mean by "use threads"? (2) What problem are you trying to solve? Commented Nov 11, 2014 at 0:37
  • Simply using a thread will not increase the speed of your database. If a RESTful call is updating every row in a table, maybe you should look at reorganizing your data so the table is referencing a foreign value that will only need updated once. Commented Nov 11, 2014 at 0:37
  • Well, java web containers are already multi threaded. I believe you're probably looking for executing asynchronous work to execute this big update. Could you please clarify so we can understand your problem better? Commented Nov 11, 2014 at 0:39
  • You will need to show what you have researched and attempted so far, by including your codes. Any answer to your current question will only raise more questions from/for you. Commented Nov 11, 2014 at 0:41
  • I put more information in my question. Thank you all. Commented Nov 11, 2014 at 5:39

1 Answer 1

5

Sure, it is possible. Are you familiar with concurrent API offered by Java?

At an high level point of view, you have to write the code that handles that Http POST. In this code, you can instantiate an arbitrary number of threads (a thread pool), and each thread of the pool makes the update on a subset of the rows to update. For example you can start 10 threads and each thread make the update on just 1000 rows.

Furthermore:

  1. I would setup the thread pool at startup of the application, so every time the POST is executed it uses the already created pool, and it does not instantiate a new one every time (it would too expensive)
  2. To assign a subset of rows to each thread, you have to use the LIMIT and START sql clauses, that let you select the subset. Each thread would have a different query based on this 2 parameters

In code:

// instantiate the pool
ExecutorService pool=Executors.newFixedThreadPool(poolSize);
// run the task to execute in parallel, specificying the subset of rows
pool.execute(new UpdateHandler(limit,skip));

// below you find a prototype of the async thread task
class Handler implements Runnable {
   private final int skip;
   private final int limit;
   Handler(int limit, int skip) { ... }

   public void run() {
     // specify the code that runs the query here
   }
 }

You can find the documentation here or here Hope this helps.

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, that was useful. Thank you but I stil have no results, beacuse is working but just for the first rows and I don't know why. I put more information in my question. Maybe that will help. Thank you.
@ErickRodriguezAvarez As you posted, you are running shutdown of thread pool before waiting the end of each thread. You should run it after all threads finished their job.
Yes, thank you, you was all rigth, but when I execute my threads, even when my thread suppouses are finished, the while loop doesn't finish. Why do yo think this is happening?
Which while loop? In the threads or the while whose condition is isTerminated() ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.