[Last Call] Learn how to a build a cloud-first strategyRegister Now


Fast dereference detection in Java

Posted on 2011-10-25
Medium Priority
Last Modified: 2012-05-12

Is there any fast way of detecting when an object loses all its references in Java?

I'm currently using the WeakReference class to allow the garbage collector to decide for me when an object is no longer referenced. The issue is that its just too slow (I've written a unit test to demonstrate this - in the test it takes a System.gc() and a Thread.sleep(200) before the get() method on the weak reference returns null - far too slow for my application).

Question by:Cheney
  • 4
  • 3
LVL 47

Expert Comment

ID: 37028283
why do you need this class WeakReference ?
Isn't it this decision a part of Java garbage collection operation?
LVL 47

Expert Comment

ID: 37028545
As far as I understand WeakReferences are used in order to maintain collections of objects that can grow too large
and also to avoid memory leask due to groups of mutually referencing objects which are not directly referenced by other objects and are unreachable can thus become permanently resident;
see here
and here:


They do not say that weak references speed up grabage collection.

which version of java are you using?

If you are concerned with garabge collection, and if you are not using Java 7, perhpas you want
to try Java 7 which has siginificantly changed garbage collection
which is getting good reviews:

LVL 47

Expert Comment

ID: 37028562

and of course follow some advice on good practices related to garbage collcetion:
this rather old but still useful papers about it:


Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.


Author Comment

ID: 37029908
Thanks for your relies :)

I'm not so much worried about garbage collection itself. What I'm trying to do is almost implement my own garbage collection for objects which use native resources.

I'm using WeakReference so that I can find out when an object is no longer used so I can recycle its native resources. The issue is that its the garbage collector who decides when weakReference.get() stops returning my object and starts returning null.

I have a reaper thread which does the following continiously:

while(!Thread.interrupted()) {
    for(NativeInfo nInfo : info) {
       if(nInfo.getWeakReference.get() == null) {


Open in new window

Problem is even after my objects are dereferenced the loop above doesn't pick them up until after the next major garbage collection - which as my heap is mostly empty doesn't happen for a very long time. As a result I run out of native resources long before any of them get recycled and my app dies.

Author Comment

ID: 37029919
Ideally I'd want recycleResources to be called the next time the reaper thread runs through the loop after the object is dereferenced by all the other threads which happen to have a strong reference to it.
LVL 10

Accepted Solution

gordon_vt02 earned 2000 total points
ID: 37031284
You probably need to add your own layer between the GC and your classes to handle native references.  Create some class to manage those resources that tracks the number of classes that have referenced the resource, then make sure those classes close() it so your class can decrement the resource counter.  Have your thread check if your reference counter is 0 and dereference at that point, or just have your resource manager handle the cleanup when the reference counter goes to 0.

This approach will give you much more consistent results than relying on the GC, especially since the GC can vary dramatically between runtime implementations and based on the selected GC algorithm.

Author Comment

ID: 37031431
That makes sense.

I wanted to avoid intermediate classes and have the client having to clean up after themselves but it looks like it's the most reliable way forward. Maybe Java 7s try with resource will make it look less messy :)

Author Closing Comment

ID: 37061814
I ended up using reference counting as suggested and hand a handler class which implemented AutoClosable manage the count and hold the reference to my natives. That way the client can use Java 7s try with resource mechanism.

Its a shame I couldn't totally remove the responsibly of cleaning up from the client but this solution is good enough.


Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Prime numbers are natural numbers greater than 1 that have only two divisors (the number itself and 1). By “divisible” we mean dividend % divisor = 0 (% indicates MODULAR. It gives the reminder of a division operation). We’ll follow multiple approac…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month18 days, 4 hours left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question