Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get the object reference count?

Tags:

java

reference

I'd like to know if there is a way to check how many references a Java object has. As far as I could check the only way to do that is using JVMTI through a JNI interface. Is there a pure Java (without using native libraries) solution to get this information?

We are developing an educational tool for data structure animation(to be used with students implementation of certain algorithms), so it would be very nice if we could check for "released" objects on the most non-intrusive way (I'm trying to avoid forcing the user of this tool to call a method such as objectReleased(objRef) in order to update the data structure animation for an element removal or something similar).

like image 861
Sergio Avatar asked Mar 17 '11 02:03

Sergio


People also ask

Do Python objects have a reference count?

Every object in Python has a reference count and a pointer to a type. We can get the current reference count of an object with the sys module. You can use sys. getrefcount(object), but keep in mind that passing in the object to getrefcount() increases the reference count by 1.

How do I get a reference count in Swift?

You can always check the reference count of a variable by using the CFGetRetainCount function. Note: Reference counting is done only to manage memory for reference types (e.g., classes and closures).

How many references can an object have?

A Formula that references a field on another object is known as a Spanning Relationship. The limit of spanning relationships per object is 15. This means that an object can only contain up to 15 different object references.


Video Answer


2 Answers

Java doesn't offer this option natively as far as I know.

Here you have some guidance on how to do it manually:

http://www.velocityreviews.com/forums/t363649-how-do-i-get-a-reference-count-of-a-object-in-java.html

like image 41
dLobatog Avatar answered Nov 08 '22 04:11

dLobatog


From your description, it seems you care less about the actual count of references than to simply know when an object has been collected. If this is the case, you can use WeakReference or PhantomReference to determine when a referenced object is ready for finalization.

See:

  • Javadoc for WeakReference: http://download.oracle.com/javase/6/docs/api/java/lang/ref/WeakReference.html
  • Javadoc for PhantomReference: http://download.oracle.com/javase/6/docs/api/java/lang/ref/PhantomReference.html
  • A great explanation of weak references: https://community.oracle.com/blogs/enicholas/2006/05/04/understanding-weak-references
  • Garbage collector callbacks: http://java.dzone.com/articles/letting-garbage-collector-do-c
  • Garbage collection notification?
like image 172
scorpiodawg Avatar answered Nov 08 '22 05:11

scorpiodawg