user8096068
user8096068

Reputation: 13

Java ExecutorService running threads twice

I have a list which is to be traversed and for each value in the list a method is to be called. Now I have put the relevant method in a thread and used executor service for parallel processing of the methods. However, for each value in the list the method ends up getting called twice for some reason.

ExecutorService service = Executors.newFixedThreadPool(NUMBER_OF_THREADS);  
for (RData rData : rDataList) {
    service.execute(new RDataUpdaterThread(rData,this.rDataProcessorGroup));
}       
service.shutdown();         
if (!service.awaitTermination(THREAD_WAIT_TIME, TimeUnit.SECONDS)) {
    service.shutdownNow(); 
}           
if(service.isTerminated()){
    if (isLockObtained) {
        try {
            rDataFetchLock.release(lockName);
            isLockObtained = false;
        } catch (FatalException e) {
            e.printStackTrace();
        }
    }
}

The code inside the run() block of the RDataUpdaterThread() is being executed twice for each value in the list. The run() block does not have any loop.

Can anyone give me the possible issues in the way I have implemented the Executor service?

Edit:

public class RDataUpdaterThread implements Runnable {
    private RData rData;
    private Thread RDataUpdaterThread;
    Session session;
    boolean postToQueue = false;

    public RDataUpdaterThread(RData rData,
            ThreadGroup threadGroup) throws InterruptedException {
        this.rData = rData;
        RDataUpdaterThread = new Thread(threadGroup, this);
        this.RDataUpdaterThread.start();
    }

@Override
public void run() {
  try{
    RDataQueueSender queueSender = new RDataQueueSender();
    session = DataAccessManager.getManager().openSession();
    RDataQueueMsg message = new RDataQueueMsg();
    RData updatedRData = updateSchedule(rData); /*postToQueue is updated here*/
    /*
        validations
        Database query
        Database insert

    */          
    if (postToQueue) {                                  
        postToQueue = false;
        message = setMessage(updatedRData);     
        int retryCount = 0; 
        while(true){
            try{
                queueSender.postRequestToQueue(message);
                break;
            }catch(Exception e){
                retryCount++;
                if(retryCount>3){
                    break;
                }
            }
        }           
    }
    }catch (Exception e) {
        e.printStackTrace();
    } finally {
        session.close();
    }
}

Upvotes: 0

Views: 313

Answers (1)

m3g4tr0n
m3g4tr0n

Reputation: 671

It's because you are starting the RDataUpdaterThread twice

First Here : service.execute(new RDataUpdaterThread(rData,this.rDataProcessorGroup));

Second Time Here : this.RDataUpdaterThread.start();

Just Remove this.RDataUpdaterThread.start();

Upvotes: 1

Related Questions