bluestring bluestring - 3 months ago 9
Java Question

How to run a method inside an object with different threads simultaneously?

My setup is as described. What I want to accomplish is have the aMethod in each of my implemented classes to run in parallel. I have looked into using

Future
s and
Runnable
and I am unsure how to proceed with either process.

My first thought was try to return a
Future<Boolean>
instead of a regular
boolean
, but I am unsure as to how would I associate the result with the name that it was initially called with.

The reason why I want aMethod to run in parallel/asynchronous is because aMethod might have a http request. If there is a request, I do not want to wait for a reply to continue. I want it to do that in a separate thread and continue on to the next method.

With a lot of http requests, aClass.doMethod() takes a while to accomplish. I want to run them in parallel so I don't have to wait for each http request before continuing.

Anyone have tips on how to accomplish this?

import java.util.ArrayList;
import java.util.List;

//Strategy.java
public interface Strategy {
boolean aMethod();
}

//AStrategy.java
public class AStrategy implements Strategy {
@Override
public boolean aMethod() {
// Do a couple http requests
return true;
}
}

//BStrategy.java
public class BStrategy implements Strategy {
@Override
public boolean aMethod() {
// Do some other requests
return true;
}
}

//SomeClass.java
public class SomeClass {
String name;
Strategy aStrategy;

public SomeClass(String name, Strategy strategy) {
this.name = name;
this.aStrategy = strategy;
}

public boolean doMethod() {
return aStrategy.aMethod();
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

//Just a regular pojo
//ResultsClass.java
public class ResultsClass {
String name;
boolean result;

public ResultsClass(String name, boolean result) {
this.name = name;
this.result = result;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public boolean isResult() {
return result;
}

public void setResult(boolean result) {
this.result = result;
}
}

public class AClass {
public static void main(String args[]) {
List<SomeClass> classes = new ArrayList<>();
classes.add(new SomeClass("Class 1", new AStrategy()));
classes.add(new SomeClass("Class 2", new BStrategy()));

List<ResultsClass> results = new ArrayList<>();
classes.forEach(aClass -> results.add(new ResultsClass(aClass.getName(), aClass.doMethod())));

}
}

Answer

The simplest way for you to do this is probably to use a ThreadPoolExecutor, make your strategy classes runnable or wrap them in runnables, and submit them to the executor. Once all are submitted, you can block on the futures until the threads complete and you can retrieve the results from the futures.