java run services in parallel on the server

I have a service which process a request from a user.

And this service call another external back-end system(web services). but I need to execute those back-end web services in parallel. How would you do that? What is the best approach?

thanks in advance

-----edit

Back-end system can run requests in parallel, we use containers like (tomcat for development) and websphere finally for production. So I'm already in one thread(servlet) and need to spawn two tasks and possibly run them in parallel as close together as possible.


I can imagine using either quartz or thread with executors or let it be on Servlet engine. What is proper path to take in such a scenario?


You can use Threads to run the requests in parallel.

Depending on what you want to do, it may make sense to build on some existing technology like Servlets, that do the threading for you


The answer is to run the tasks in separate threads.

For something like this, I think you should be using a ThreadPoolExecutor with a bounded pool size rather than creating threads yourself.

The code would look something like this. (Please note that this is only a sketch. Check the javadocs for details, info on what the numbers mean, etc.)

// Create the executor ... this needs to be shared by the servlet threads.
Executor exec = new ThreadPoolExecutor(1, 10, 120, TimeUnit.SECONDS,
        new ArrayBlockingQueue(100), ThreadPoolExecutor.CallerRunsPolicy);

// Prepare first task
final ArgType someArg = ...
FutureTask<ResultType> task = new FutureTask<ResultType>(
        new Callable<ResultType>() {
            public ResultType call() {
                // Call remote service using information in 'someArg'
                return someResult;
            }
});
exec.execute(task);

// Repeat above for second task
...
exec.execute(task2);

// Wait for results
ResultType res = task.get(30, TimeUnit.SECONDS);
ResultType res2 = task2.get(30, TimeUnit.SECONDS);

The above does not attempt to handle exceptions, and you need to do something more sophisticated with the timeouts; eg keeping track of the overall request time and cancelling tasks if we run over time.


This is not a problem that Quartz is designed to solve. Quartz is a job scheduling system. You just have some tasks that you need to be executed ASAP ... possibility with the facility to cancel them.


Heiko is right that you can use Threads. Threads are complex beasts, and need to be treated with care. The best solution is to use a standard library, such as java.util.concurrent. This will be a more robust way of managing parallel operations. There are performance benefits which coming with this approach, such as thread pooling. If you can use such a solution, this would be the recommended way.

If you want to do it yourself, here is a very simple way of executing a number of threads in parallel, but probably not very robust. You'll need to cope better with timeouts and destruction of threads, etc.

public class Threads {
    public class Task implements Runnable {
        private Object result;
        private String id;

        public Task(String id) {
            this.id = id;
        }

        public Object getResult() {
            return result;
        }

        public void run() {
            System.out.println("run id=" + id);
            try {
                // call web service
                Thread.sleep(10000);
                result = id + " more";
            } catch (InterruptedException e) {
                // TODO do something with the error
                throw new RuntimeException("caught InterruptedException", e);
            }
        }
    }

    public void runInParallel(Runnable runnable1, Runnable runnable2) {
        try {
            Thread t1 = new Thread(runnable1);
            Thread t2 = new Thread(runnable2);

            t1.start();
            t2.start();

            t1.join(30000);
            t2.join(30000);
        } catch (InterruptedException e) {
            // TODO do something nice with exception
            throw new RuntimeException("caught InterruptedException", e);
        }
    }

    public void foo() {
        Task task1 = new Task("1");
        Task task2 = new Task("2");

        runInParallel(task1, task2);

        System.out.println("task1 = " + task1.getResult());
        System.out.println("task2 = " + task2.getResult());
    }
}
链接地址: http://www.djcxy.com/p/35386.html

上一篇: 并行运行任务的组实例

下一篇: java在服务器上并行运行服务