java - 如何使用 ExecutorService 在多个线程中将元素正确添加到 ConcurrentHashMap
问题描述
我正在尝试使用多个线程将图像从某个文件夹加载到 ConcurrentHashMap 以节省时间。不幸的是,一些线程在尝试加载并将图像放入我的地图时“卡住”。结果,当调用 shutdown() 程序时,即使某些线程没有执行它们的任务,程序也会走得更远。当我将 ExecutorService 线程 pule 设置为 1 时,一切正常,但我浪费了大量时间等待加载所有图像。在我看来,存在一些竞争问题,但我知道 ConcurrentHashMap 对于多线程操作是安全的。我仍然是初学者,所以请让我了解问题出在哪里以及我做错了什么。这是代码:
public abstract class ImageContainer {
private final static Map<String, BufferedImage> imageMap = loadImages();
private static long loadingTime;
public static Map<String, BufferedImage> loadImages() {
loadingTime = System.currentTimeMillis();
ConcurrentHashMap<String, BufferedImage> imageMap = new ConcurrentHashMap<>();
ExecutorService es = Executors.newFixedThreadPool(5);
File imageDirectory = new File("Images/");
if (!imageDirectory.isDirectory()) {
System.out.println("Image directory error");
}
File[] files = imageDirectory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isFile()) {
es.submit(new Runnable(){
@Override
public void run() {
try{
if(file.getAbsolutePath().contains(".jpg")) {
imageMap.put(file.getName().replace(".jpg",""),ImageIO.read(file));
}
else if (file.getAbsolutePath().contains(".png")) {
imageMap.put(file.getName().replace(".png",""),ImageIO.read(file));
}
}
catch (IOException e)
{
System.out.println("Cannot load image");
}
}
});
}
}
}
else
{
System.out.println("Image folder empty!");
}
es.shutdown();
try {
if(!es.awaitTermination(5L, TimeUnit.SECONDS)) {
System.out.println("Images did not load successfully!");
es.shutdownNow();
}
loadingTime = System.currentTimeMillis() - loadingTime;
}
catch(InterruptedException e) {
System.out.println("Loading images interrupted!");
}
System.out.println(imageMap.size());
return imageMap;
}
};
解决方案
这个问题很可能与ConcurrentHashMap
. 每次,你put
在地图上的东西,没有其他线程将能够put
并发。所以也许,一些线程将不得不等到另一个线程完成put
,但这不会导致任何竞争条件。
我在我的机器上执行了你的代码,一切正常。(没有错误消息,打印加载图像的数量)。也许您的计算机在加载图像方面不如我的快,因此awaitTermination
超时。
据我所知,我不知道您的方法(使用多线程加载图像)是否是个好主意。您的硬盘驱动器(或 SSD)将成为瓶颈,您的线程最终将等待硬盘驱动器(语句ImageIO.read
)。此外,启动执行器服务(分别启动新线程)并不是很便宜,所以也许你最好不使用多线程。特别是因为您只需要加载一次图像(之后,它们被缓存在地图中),因此加速可能永远不会显着。我会考虑按顺序加载图像。
推荐阅读
- java - 测试时出现空指针异常?
- python - Python,如何找到3维数组的维数?
- unix - 如何验证使用 FTP 提交到 z/OS 的作业是否已完成?
- python - 字符串切片不接受变量
- javascript - 将数据从服务传递到控制器 AngularJS 1.3.15
- javascript - 是否有适用于微软 BotFramework 的 Web 客户端 SDK
- jvm - 组装 jasmin 类导致倒置运算符和比较
- python - 我想从 main_program.py 修改我自己的 my_dicts.py 模块
- swift - MobileFFMPeg 未将 mkv 转换为 Mp4
- django - 如何上传“django-rest-api server”和“crawling.py”