我真正想弄清楚的是如何思考这个问题,或者从在这个领域有更多经验的人那里得到一些见解。
假设这是一个 Web 服务中的单例类,就像一个 graphql 数据获取器。哪个在规模上更高效:第一个还是第二个?或者会有什么性能差异?
public class FooBarClass {
public List<Bar> getSomeStuff() {
List<Bar> bar = new ArrayList<Bar>;
final ExecutorService threadpool = Executors.newFixedThreadPool(10);
//Get the stuff in multithreaded way.
threadpool.shutdown();
return bar;
};
}
}
Run Code Online (Sandbox Code Playgroud)
或者
public class FooBarClass {
final ExecutorService threadpool = Executors.newFixedThreadPool(10);
public List<Bar> getSomeStuff() {
//...
//Get the stuff using the executor service.
return bar;
};
}
}
Run Code Online (Sandbox Code Playgroud)
我发现使用 executor 服务肯定会加速代码。我们正在执行类似批处理的提取,但由于某些原因我们需要进行单次提取,因此所有提取都是异步的。