Multithreading – managing threads in Grails services
So I have a service setting to import a large amount of data from the files uploaded by users I want users to continue working on the website while processing files I did this by creating a thread
Thread.start { //work done here }
The problem now is that I don't want to run multiple threads at the same time This is what I tried:
class SomeService { Thread thread = new Thread() def serviceMethod() { if (!thread?.isAlive()) { thread.start { //Do work here } } } }
But that won't work thread. Isalive() always returns false What ideas can be realized?
Solution
I will consider using executor
import java.util.concurrent.* import javax.annotation.* class SomeService { ExecutorService executor = Executors.newSingleThreadExecutor() def serviceMethod() { executor.execute { //Do work here } } @PreDestroy void shutdown() { executor.shutdownNow() } }
Using newsinglethreadexecution will ensure that tasks are executed one after another If the background task is already running, the next task will be queued and started when the running task is completed (the servicemethod itself will still return immediately)
If your "work here" involves Gorm database access, you may want to consider the executor plugin, which will set the appropriate persistence context for background tasks (such as hibernate sessions)