【发布时间】:2020-06-05 17:40:28
【问题描述】:
这是我当前工作代码的伪代码版本:
public class DataTransformer {
private final boolean async = true;
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
public void modifyAsync(Data data) {
if (async) {
executorService.submit(new Runnable() {
@Override
public void run() {
modify(data);
}
});
} else {
modify(data);
}
}
// This should actually be a variable inside modify(byte[] data)
// But I reuse it to avoid reallocation
// This is no problem in this case
// Because whether or not async is true, only one thread is used
private final byte[] temp = new byte[1024];
private void modify(Data data) {
// Do work using temp
data.setReady(true); // Sets a volatile flag
}
}
请阅读 cmets。但现在我想使用Executors.newFixedThreadPool(10) 而不是Executors.newSingleThreadExecutor()。在我的情况下,这很容易通过将字段temp 移动到modify(Data data) 中来实现,这样每次执行都有自己的temp 数组。但这不是我想做的,因为我想尽可能重用数组。相反,我希望 10 个线程中的每一个线程都有一个 temp 数组。实现这一目标的最佳方法是什么?
【问题讨论】:
-
您可以使用
ThreadLocal或其他一些池化机制。 -
Re, "...但我重复使用它以避免重新分配。"在重新使用
temp数组而不是为每个任务分配一个新数组时,您是否测量任何性能改进? Java 程序创建大量短期对象是正常的,堆和垃圾收集器经过优化以有效处理这种情况。 -
在这种特殊情况下,如果不进行池化,它可能会更快。但是我也很好奇这个基本怎么实现。
-
@stonar96,所以你想在线程之间共享数据吗?
-
你可以将 temp 声明为 static 或者如果你想使用不同的值然后使用 threadlocal
标签: java multithreading resources thread-safety executorservice