【发布时间】:2019-02-14 06:24:54
【问题描述】:
我在多线程环境中有一个有趣的内存泄漏案例。 我有以下逻辑:
public void update(string key, CustomObj NewResource)
{
//fetch old resource for the given key from the concurrent hashmap
// update hashmap with the newResource for the given key
// close the old resource to prevent memory leak
}
public void read (string key)
{
// return resource for the given key
}
现在如果我有两个线程:
Thread#1:调用 update 方法更新 key K 的资源
Thread#2:调用read方法读取同一个key K的资源。
注意:CustomObj 属于第三方库,所以我不能在其中放入 finalize 方法来关闭它。
即使在读取和更新方法上使用同步也无济于事,因为更新线程可以在读取线程仍在使用资源时关闭资源。
您能告诉我在这种情况下如何在不发生内存泄漏的情况下保持线程安全吗?
【问题讨论】:
-
只要让reader线程在读完资源后负责关闭资源
-
@ErwinBolwidt 我认为这行不通。我们可以让多个阅读器同时进行读取操作。由于资源尚未过时,读者没有必要关闭。
标签: java multithreading memory-leaks