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
}