In java, what happens when an object is deleted while using it?
Here's the script:
-
I have a java Hashtable that takes string as key and object as value.
-
One thread receives an object using a key and calls a method on that object.
-
while the method is doing some operation from step b), another thread causes the deletion of that particular key that refers to the object.
What's happening?
Should I put a lock on the operation?
source to share
You cannot delete objects in Java. The reason you haven't run out of memory is because the garbage collector will remove them for you when you're not looking - this means that if you could indicate in any way that the object was removed, it won't get removed. (Apart from things designed for this purpose, such as finalize
and WeakReference
).
Removing an object from a Hashtable only affects the Hashtable; it has no effect on the actual object, and in particular it does not delete the object.
source to share
What actually happens depends on what you have specified. In particular, if step 2 has no before-before to step 3, it is possible that the value was removed from your map before step 2 begins.
Assuming the data structure in step 3 is thread safe (what Hashtable
), there will be no problem with step 3; it will delete the entry successfully. However, step 2 can run into problems without explicit blocking. For example, if you call containsKey()
before a call get()
and step 3 runs between the two calls, the behavior of step 2 will be inconsistent. This is called a race condition .
There are many ways to enforce communication between events (one of which is actually locking), but what you need will depend on your requirements.
As an aside, there is little use for it Hashtable
; it is an old, slow implementation Map
that has little benefit over the standard alternatives.
If your mapped data will only be available on one thread (or you will be using synchronous access with a custom lock), use HashMap
. If your mapped data will be shared between threads use ConcurrentHashMap
.
source to share