简体   繁体   中英

Concurrency through ExecutorService in Java

I'm using below concurrency feature of Java 1.6 to execute some task offline. 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).

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.

Is it ok to use the similar above code with 4 different inner classes & perform offline activity within them?? 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.

I've successfully used Executors with pools successfully earlier in a web-application. 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.

Example

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

You can also read this nice article: Java Concurrency

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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