管理Grails服务中的线程 [英] Managing threads in Grails Services

查看:90
本文介绍了管理Grails服务中的线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一项服务设置为从用户上传的文件中导入大量数据。我希望用户能够在文件正在处理时继续在网站上工作。

  Thread.start {
//在这里完成的工作
}

现在问题出现了,我不想让多个线程同时运行。这是我试过的:

  class SomeService {

Thread thread = new Thread()
$ b $ def serviceMethod(){
if(!thread?.isAlive()){
thread.start {
//在这里工作
}

}

}

然而,没有工作。 thread.isAlive()总是返回false。关于如何实现这一点的任何想法?

解决方案

我会考虑使用 Executor
$ $ p $ import java.util.concurrent。*
import javax.annotation。*

class SomeService {

ExecutorService executor = Executors.newSingleThreadExecutor()
$ b $ def serviceMethod(){
executor.execute {
/ / Do work here



$ b @PreDestroy
void shutdown(){
executor.shutdownNow()
}




使用 newSingleThreadExecutor
code>将确保任务一个接一个地执行。如果后台任务已在运行,则下一个任务将排队等待,并在运行任务完成时开始( serviceMethod 本身仍将立即返回)。



如果您的do可能需要考虑执行器插件在这里工作涉及GORM数据库访问,因为该插件将为您的后台任务设置适当的持久化上下文(例如Hibernate会话)。


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 processed. I accomplished this by creating a thread.

Thread.start {
 //work done here
}

Now the problem arises that I do not want to have multiple threads running simultaneously. Here is what I tried:

class SomeService {

Thread thread = new Thread()

 def serviceMethod() {
   if (!thread?.isAlive()) {
     thread.start {
        //Do work here
     }
   }
 }

}  

However, this doesn't work. thread.isAlive() always return false. Any ideas on how I can accomplish this?

解决方案

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.

这篇关于管理Grails服务中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆