How to parallelize this groovy code?

I'm trying to write a reusable component in Groovy to easily strip emails from some of our Java applications. I would like to give him a list where the email is just POJO (POGO?) With some emails. I would like it to be multi-threaded, at least to execute all the email logic in a second thread, or do one thread per email.

I am really fogging over multithreading in Java, so this probably won't help! I tried several different ways, but here is what I have right now:

void sendEmails(List<Email> emails) {

    def threads = []

    def sendEm = emails.each{ email ->
        def th = new Thread({
            Random rand = new Random()
            def wait = (long)(rand.nextDouble() * 1000)
            println "in closure"
            this.sleep wait
            sendEmail(email)
        })
        println "putting thread in list"
        threads << th
    }

    threads.each { it.run() }
    threads.each { it.join() }

}

I was hoping that sleep would randomly slow down some threads, so console output would not be consistent. Instead, I see the following:

putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
putting thread in list
in closure
sending email1
in closure
sending email2
in closure
sending email3
in closure
sending email4
in closure
sending email5
in closure
sending email6
in closure
sending email7
in closure
sending email8
in closure
sending email9
in closure
sending email10

sendEmail , , println, , ,

void doSomething() {

    Mailman emailer = MailmanFactory.getExchangeEmailer()

    def to = ["one","two"]
    def from = "noreply"

    def li = []
    def email   
    (1..10).each {
        email = new Email(to,null,from,"email"+it,"hello")
        li << email
    }

    emailer.sendEmails li
}
+3
2

, ,

threads.each { it.run() }

threads.each { it.start() }

as run() , , .

Groovy, GPars. concurrency, Fork/Join Actor. GPars, :

def sendEmails(emails) {

  GParsPool.withPool {
    emails.eachParallel { email ->
      def wait = (long) new Random().nextDouble() * 1000 
      println "in closure"
      this.sleep wait
      sendEmail(email)
    }
  }

}
+10

Java (1.5) concurrency, Java ( ) . Google java ThreadExecutor, , :

http://www.deitel.com/articles/java_tutorials/20051126/JavaMultithreading_Tutorial_Part4.html

Groovy , , "" Java Java, .

+2

Source: https://habr.com/ru/post/1747228/


All Articles