简体   繁体   English

通过Java中的ExecutorService进行并发

[英]Concurrency through ExecutorService in Java

I'm using below concurrency feature of Java 1.6 to execute some task offline. 我正在使用Java 1.6的以下并发功能离线执行一些任务。 When the user is created through registration, I need to perform some inhouse logging task & I don't want to block the user, so I've been using the below code 通过注册创建用户时,我需要执行一些内部日志记录任务,并且我不想阻止该用户,因此我一直在使用以下代码

    java.util.concurrent.ExecutorService myservice = Executors.newSingleThreadExecutor();
    myservice.execute(new myTask(user));

Here, I'm having an inner class myTask which implements Runnable & in Run method, I'm doing offline activity (thus making it as a non-blocking call). 在这里,我有一个内部类myTask,它实现了Runnable&in Run方法,并且正在进行离线活动(因此将其作为非阻塞调用)。

Now, once the user logs in to website, there are certain actions (buttons on web pages) clicking on which I need to do similar offline activities & I don't want to make the call as a blocking call. 现在,一旦用户登录到网站,就可以单击某些操作(网页上的按钮),然后单击它们,我需要进行类似的脱机活动,并且我也不想将该呼叫作为阻止呼叫。 I've 4 actions on this page on which I need to perform offline tasks. 我在此页面上有4个动作,我需要在这些动作上执行离线任务。

Is it ok to use the similar above code with 4 different inner classes & perform offline activity within them?? 将上面类似的代码与4个不同的内部类一起使用并在其中执行离线活动是否可以? If not, whats the alternative? 如果没有,那还有什么选择?

Thanks! 谢谢!

You can use Executors if you are not expecting high level of concurrent requests. 如果您不希望出现高水平的并发请求,则可以使用执行器。 Use Thread pool in this case. 在这种情况下,请使用线程池

If yours is a highly-concurrent app and you should guarantee the processing of the action (even in case of jvm crash) and you want the actions to be transactional then messaging (JMS) might be the solution. 如果您的应用程序是并发性很高的应用程序,那么您应该保证动作的处理(即使在jvm崩溃的情况下),并且希望动作是事务性的,那么消息传递(JMS)可能是解决方案。

I've successfully used Executors with pools successfully earlier in a web-application. 我已经成功地在Web应用程序中成功地将Executors与池一起使用了。 It is however not recommended to create threads in a web-app and not allowed in an EJB as the threads are not managed by the container. 但是,不建议在Web应用程序中创建线程,并且不建议在EJB中创建线程,因为线程不是由容器管理的。

Example

static final int POOL_SIZE=10;
ExecutorService pool = Executors.newFixedThreadPool(POOL_SIZE);

You can also read this nice article: Java Concurrency 您还可以阅读这篇不错的文章: Java并发

除了线程池之外,您还应该使用线程安全队列来允许比可用线程更多的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM