OneTwo
OneTwo

Reputation: 2483

How to execute the same method concurrently in Java

sorry if this is a very basic/stupid question.

I have a method which takes a number of minutes to run. I'd like to run this method on multiple objects concurrently. I'm wondering how I go about doing this? Even just a pointer to the right documentation. I'm not sure if I should use threads, or ExecuteService or what.

Heres the method I would like to run concurrently. I want to delete multiple vm's concurrently.

private void deleteVm(String workspace, String vmName) {
    println("Delete VirtualMachine: " + vmName + " in Workspace " + workspace);
    Job job = executeDelete(getWorkbench().deleteVirtualMachine(sub(), workspace, vmName));
    println(job);

    subscribeToJobLogs(job);

    awaitUntilJobNotRunningOrNotFound(() -> executeCall(getWorkbench().getVirtualMachineDeleteJob(sub(), workspace, vmName)));
}

Upvotes: 1

Views: 3401

Answers (2)

HPCS
HPCS

Reputation: 1454

If you want call method concurrently you need threads. Java documentation for concurrency: https://docs.oracle.com/javase/tutorial/essential/concurrency/index.html.

You have many options how to create/use threads in java.

1) if you know how many threads do you need you can create threads manually like this:

Thread thread1 = new Thread(()->deleteVm("a","b");
Thread thread2 = new Thread(()->deleteVm("c","d");

//START the threads
thread1.start();
thread2.start();

2) you can use default threads pool(usually thread per cpu core) like this:

CompletableFuture.runAsync(() -> deleteVm("a", "b"));
CompletableFuture.runAsync(() -> deleteVm("c", "d"));

3) you can create your own thread executor like this

ScheduledExecutorService executorService = Executors.nScheduledExecutorService executorService = Executors.newFixedThreadPool(5)

executorService.submit(() -> deleteVm("a", "b"));
executorService.submit(() -> deleteVm("c", "d"));

Upvotes: 3

Vitalii Vitrenko
Vitalii Vitrenko

Reputation: 10395

The easiest way is to use CompletableFuture

CompletableFuture.runAsync(() -> deleteVm("one", "two"));
CompletableFuture.runAsync(() -> deleteVm("three", "four"));

Upvotes: 3

Related Questions