Can I use multithreading to call the same call at the same time?
I am using java and am about to make some rest calls using Zephyr api. I don't think the api used will affect the possibility of my question. I'm just wondering if it is possible to use the same call at the same time to be called again using multithreading? Each call will retrieve different data, they do not all grab the same data.
It's just for getting data, not writing.
If possible, what are the risks? Is this recommended?
source to share
Of course, this will improve your performance if you implement it correctly. As mentioned, you just need to be careful with the implementation to avoid security and performance issues. I suggest having a thread pool, so you can manage many threads that make the REST calls that you make at the same time.
ThreadPoolExecutor
will be helpful.
You can use Executors.newFixedThreadPool
/ Executors.newCachedThreadPool
. They both work great.
You can create a task (injection Callable
) to perform your REST activation or call and then use invokeAll(
) ThreadPoolExecutor
(This is where you would like to include the task list).
Hope this helps you.
Sincerely.
source to share
As others have pointed out, yes it is doable, but you should be aware of the possible load that you would put on the server.
One solution I've used for this kind of thing in the past is a work queue of one kind or another. For example:
ExecutorService es = Executors.newFixedThreadPool(MAX_THREADS);
for (final Thing thing : things) {
es.submit(new Runnable {
@Override
void run() {
doSomething(thing);
}
});
}
es.shutdown();
What does it do:
- Uses
Executors.newFixedThreadPool(int)
to create a newExecutorService
one that will process up to theMAX_THREADS
task in parallel. - Iterates over the list of "things" to work with (regardless of whether they are domain specific) and creates a new anonymous class
Runnable
to calldoSomething(thing)
for each one. Here is where you make your calls to the server and do whatever work you have to do. - Summons
ExecutorService.shutdown()
to informExecutorService
us that we have finished giving him something to do. If you want to wait for all of these tasks to complete, seeExecutorService#awaitTermination(long, TimeUnit)
See also: Thread pools
source to share