-2

i have a spring boot aplication and i want send email with javamail using ses on aws. but if I send an email, while it and sent no other process is executed. I want to send the email through a thread, but I've implemented a thread in this way and even then the email sending process is not asynchronous. when I make this request to send email and then list all to see how the processing is, as long as the sending of the email does not finish the list request is not executed

@GetMapping
public ResponseEntity<?> listarUsuarios(){
    System.out.println("--------begin send mail------------");
    new SendMail(emailService).run();
    System.out.println("--------finish send mail------------");
    List<Usuario> usuariosList = usuarioRepository.findAll(); // <- this process not is processed when send email not finish
    return new ResponseEntity<>(usuariosList,HttpStatus.OK);
}

.

public class SendMail extends Thread {
    public EmailService emailService;
    public SendMail(EmailService emailService) {
        this.emailService = emailService;
    }
    public void run(){
        try {
            emailService.EnviarEmailDeConfirmacao("daviresio@gmail.com", 1, "Subject test mail","body test mail");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Davi Resio
  • 653
  • 2
  • 11
  • 21
  • 2
    Possible duplicate of [What is the difference between Thread.start() and Thread.run()?](https://stackoverflow.com/questions/2674174/what-is-the-difference-between-thread-start-and-thread-run) – xingbin Apr 23 '18 at 12:46

4 Answers4

3

You are not starting a new thread. Instead, you are calling the run() method directly:

new SendMail(emailService).run();

Call start() instead to start a new thread:

new SendMail(emailService).start();

By the way, starting new threads like this from a web application is bad practice. It's better to use for example an ExecutorService to manage the threads that send e-mails, so that you don't get a potentially unlimited number of threads when many users are calling this functionality at the same time.

Jesper
  • 202,709
  • 46
  • 318
  • 350
1

new SendMail(emailService).start(); - will start a new Thread and will execute SendMail.run(); in the new Thread.

new SendMail(emailService).run(); - is just a method call which executed in the same thread.

J-Alex
  • 6,881
  • 10
  • 46
  • 64
1

You should use the start() method to spawn as a new thread. If you call run() directly it is run in the same thread. See https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html

Jotunacorn
  • 496
  • 1
  • 4
  • 12
1

Use start() instead of run().

  • Run will execute it on the existing thread.

  • Start will execute it on a new thread.

So change your code to the following if you want it to execute asynchronous:

new SendMail(emailService).start();
stefana
  • 2,606
  • 3
  • 29
  • 47