Erick Rodriguez
Erick Rodriguez

Reputation: 198

Use threads on a RESTful Web Service in Java

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.

Upvotes: 1

Views: 18988

Answers (1)

Giovanni Bitliner
Giovanni Bitliner

Reputation: 2072

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.

Upvotes: 5

Related Questions