Jordendarc
Jordendarc

Reputation: 37

How to multithread in Groovy correctly

I have tried multithreading by doing the following:

        def resultSet = [
                valid: [],
                invalid: []
        ]
        List<Thread> threads = []
        items.each { OrionEquipmentTO item ->
            threads << Thread.start {
            def validation = validators.any { validator ->
                if (validator.validate(item, message)) {
                    //println "this is item is invalid due to ${validator.class}"
                    resultSet.invalid.add(item)
                    return true
                }
            }
            if (!validation) {
                resultSet.valid.add(item)
            }
        }
        threads.each { it.join() }
        println "validated ${items.size()} --- valid: ${resultSet.valid.size()} , invalid: ${resultSet.invalid.size()}"

when I run this, the resultset valid + invalid size is 4 items less than items total size. without the threading, it has valid sizes, but takes forever longer

Upvotes: 0

Views: 1063

Answers (1)

Chayne P. S.
Chayne P. S.

Reputation: 1638

Normally Groovy list is ArrayList which is not thread-safe. Can use CopyOnWriteArrayList instead.

def resultSet = [
                valid: [] as CopyOnWriteArrayList,
                invalid: [] as CopyOnWriteArrayList,
        ]

...

Upvotes: 3

Related Questions