How can i achieve parallelism in synchronous operation in JAVA lets example I have a loop
List<Integer> a= new ArrayList()<>;
for(int i=0;i< 100; i ){
a.add(i)
}
after that i have save operation in DB, like Plan.setA(a)
how can i optimise it?How can i make this synchronous call into multiple thread? Can someone help me in solving problem using above example
CodePudding user response:
You can use ExecutorService
to run this async
List<Integer> a = new ArrayList<>();
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
for (int i = 0; i < 100; i ) {
a.add(i);
}
});
executor.shutdown();
You would create a new ExecutorServic
e using the newSingleThreadExecutor
method, which creates a single-threaded executor that executes tasks in a single worker thread operating off an unbounded queue. Then, submit the lambda function containing the code to be executed asynchronously to the executor using the submit method. Finally, shut down the executor using the shutdown method.
Here is the official documentation https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html
CodePudding user response:
Seems like you want to create a list of integers?
IntStream.range(0, 100).boxed().collect(Collectors.toList());