Reputation: 3165
I have a interesting case of memory leak in a multi threading environment. I have following logic:
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
}
Now if I have two threads:
Thread#1: calling update method to update the resource for key K
Thread#2: calling read method to read the resource for the same key K.
Note: CustomObj belongs to a third party library so I cant put finalize method in it for closing it.
Even using synchronization on read and update method wont help because the update thread can close the resource while the read thread is still using it.
Could you please tell how to maintain thread safety without memory leak in this scenario ?
Upvotes: 0
Views: 506
Reputation: 15663
You should never use finalize()
for reasons too broad to discuss here.
If several threads can work with one object at the same time, then you can use "reference counting" to track when the resource should be closed.
Every thread/function/etc that currently works with the object increments its "users count" with one when it acquires access to the object. When it stops working with it, then it decrements its "users count" by one. The thread that decremented the count to zero closes the object. You can take advantage of the various "atomic" primitives provided by the java standard library in order to create a lock-free solution.
As this an object from a third pary library, you'll need to create some kind of wrapper to track the references.
PS: Usually it's not a good idea to use objects with shared state across threads - it begs for trouble - synchronization issues, data races, performance lost in synchronization, etc.
Upvotes: 1