Home > Back-end >  How to write run two thread simultaneously when second thread is using first thread info
How to write run two thread simultaneously when second thread is using first thread info

Time:06-10

Can you please help me on below? thread--1 data=//it is fetching data from database side
thread-->2 logic to use use above data and perform updation Can we write a code so that it can fetch data and perform updation simultaneously?

public static void getChildren(){
    //some code Thread-->1 
    List<Employee> name=null;
    name=ProjectReleaseCache().getProjectreleasedataCache().get50EmpName(batchlistId);
    //fetching name from database in batch of 50 Thread-->2
    for (Employee nm: name) {
        name =";";
    }
} 

In above code "batchlistId" is the batch of 50 ids for which we are fetching name and then for 50s name we are updating name in second thread. I want to write a code so that it can fetch Id and update name simultaneously

CodePudding user response:

Sounds like one thread produces data items while the other one should consume it. A double ended queue (deque) should help in this case.

I faintly recall there was one implementation that would block a producer if the queue was full and block a consumer if the queue was empty. Somehow I cannot tell which class it was right now...

CodePudding user response:

Try a ThreadPoolExecutor.

You create instances of these by using the Executors class.

This would look something like:

public class SomeClass{
    // 10 could be a lot or not enough here, you'll need to tune this for your scenario.
    private final ExecutorService executor = Executors.newFixedThreadPool(10);
    
    public void startEmployeeProcessing(){
        while(/*some condition*/){
            List<Employee> employeeBatch = /* get a batch of employees */
            queueEmployees(employeeBatch);
        }
    }

    private void queueEmployees(List<Employee> employees){
        executor.submit(() -> modifyEmployees(employees));
    }

    private void processEmployees(List<Employee> employees){
        for(Employee employee:employees){
            //do whatever you need to employees
        }
    }
}

Be sure that each thread has its own db connection and transactions.

Depending on your persistence layer, if you can, persist in batches as well, as this will speed things up too.

  • Related