Managing threads in Grails Services

后端 未结 2 1751
长情又很酷
长情又很酷 2021-02-08 03:12

So I have a service set up to import a large amount of data from a file the user uploads. I want to the user to be able to continue working on the site while the file is being p

2条回答
  •  無奈伤痛
    2021-02-08 03:35

    I would consider using an Executor instead.

    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 a newSingleThreadExecutor will ensure that tasks execute one after the other. If there's a background task already running then the next task will be queued up and will start when the running task has finished (serviceMethod itself will still return immediately).

    You may wish to consider the executor plugin if your "do work here" involves GORM database access, as that plugin will set up the appropriate persistence context (e.g. Hibernate session) for your background tasks.

提交回复
热议问题