简体   繁体   中英

Multhreading a java rest service

I'm new to java and am building a java rest service using the CXF JAXRS library.

I would like the the service to be able to consume multiple http request at a time. How do I achieve this?

Do I need to host the service in a web container? Or can I achieve multithreading even if I run the service without(preferable) a web container ?

Thanks

You have to modify the architecture of your application to process multiple requests at one time and meanwhile save the incoming requests for future processing.

Implement the Master-Worker Pattern, which will solve your problem. You can follow these steps to implement this pattern(Its an approach not algorithm):

1) Use Executor Framework of Java 5 or Fork Join from Java 7 as per your wish. Say we are using java 5.

2) Use a shared queue to save data(say some work object) temporarily for future use. I have used BlockingQueue which is thread-safe.

3) Create a master class, which will start and stop the multiple instances(n) of workers. When a new request is received, master will put the data in work object and will add this work object to queue. At the time of adding work object to queue, master will call notifyAll method on this queue (to awake all waiting workers).

4) Create a worker thread class which will listen on this queue (By giving reference to shared queue in its constructor). Fetch work objects one by one from queue until queue is empty. Put worker in wait state while queue is empty. When Master will call notifyAll method on this queue, it will again go live.

Let me know if you need any other clarification.

One Simple Example of Executor Framework(Not Master Worker Pattern) is here

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