R H
R H

Reputation: 397

Is there anyway to find out number of threads are using the object currently ?

Basically I want to find out how many threads are using the object currently. If nobody is using this object reference, then I want to destroy this object.

Example

 User u = new User();
 (here I have other code) 
 if (u is not used by any thread) {
   u = null;
 }

Upvotes: 1

Views: 131

Answers (1)

Stephen C
Stephen C

Reputation: 718906

This Question is based on a fundamental misunderstanding of Java memory management.

Assigning null to a variable does NOT destroy the object it previously referred to. What it actually does is to break one of possibly many paths (chains of references from live variables) to the object that make it "reachable". When no more paths exist, the object cannot be reached (used) by anything in the program and is eligible to be garbage collected. When it actually goes away is at the discretion of the JVM / garbage collector.

You are trying to make the User object "go away" when nothing else has its reference. But that is going to happen anyway. All you really need to do is to unconditionally assign null to u so that this variable doesn't stop the User object going away.

Can you make the User object go away "now"? Well the answer is complicated, by it boils down to:

  • you can't do it reliably, and
  • you can't do it efficiently.

And to answer the question in the question title.

Is there anyway to find out number of threads are using the object currently ?

No. Not in the sense that you mean. The JVM doesn't even provide a way to find out how many live copies of the Object's reference there are. The closest that the JVM comes to providing this are the SoftReference and WeakReference classes that can be used to detect that an object no longer has any normal (strong) references to it.

But this is not necessary for solving your "problem".

Upvotes: 6

Related Questions