0

How can I optimize a java treatment (for loop, nested loop) and execute it in the background so I can continue with another treatment?

@Transactional(propagation = Propagation.REQUIRES_NEW,
        readOnly = false, rollbackFor = AppTechnicalException.class)
public void update(FicheDTO dto, String code) throws {
    Fiche fiche = this.ficheDAO.find(fiche.getNumero());

    this.traitementToDO(dto, fiche);

    Tracabilite trace = createTraceF(fiche.getNumero(), code);
}

I want that this.traitementToDO(dto, fiche) to run in the background!

Community
  • 1
  • 1
Ahmed
  • 25
  • 1
  • 5

3 Answers3

0

In order to compute multiple tasks in parallel in Java, you can use threads. By creating a new thread you can run your long tasks asynchronously and then notify when the execution of your tasks is done. For more info about threads, see this.

Tristan Bilot
  • 479
  • 5
  • 16
0

You can try this -

@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = AppTechnicalException.class)
public void update(FicheDTO dto, String code) throws {

    Fiche fiche = this.ficheDAO.find(fiche.getNumero()) ;

    Thread demonThread = new Thread(() -> traitementToDO(dto, fiche));
    /*new Runnable() {
        @Override
        public void run() {
            traitementToDO(dto, fiche);
        }
    }); //lambda like anonimus class */

    daemonThread.setDaemon(true); // run as demon if needed
    daemonThread.start(); // execute method in another child thread
    

    Tracabilite trace = createTraceF(fiche.getNumero(), code);
}

BUT Think about @Transactional: If you need to cover traitementToDO by transaction, you cannot call it via this, because you have no access to spring proxy inside this bean. So you need to do self autowiring and then call it via self.traitementToDO. Also, be careful with custom multithreading if you don't know how to use Threads. Finally, you need to read how to use @Transactional in multithreading (if you need to cover traitementToDO by transaction again).

Dmytro Bill
  • 101
  • 4
0

If you have a list of some objects, you can parallelize their processing with a parallel stream like this:

List<FicheDTO> list = List.of(...);
String code = "UPDATE ...";

list.stream().parallel().forEach(dto -> update(dto, code));