8

I approached it similar to the case of deleting any usual object, ie, simply making the reference null and letting the Garbage Collector do its job.

However for equating to null within a class, the only reference to the object is "this". So is the code for the following class valid:

class A{
  public A(){
    //Init
  }

  public void method destruct(){
    if(someCondition){
      this=null;  //Is this statement valid? Why / Why not?
    }
  }
}
SimplyPanda
  • 725
  • 7
  • 16
Saurabh Agarwal
  • 507
  • 2
  • 5
  • 16
  • 1
    If `this` is *truly* the only reference to the object, then you're done: it's eligible for GC as soon as your leave the method and will be removed eventually. – Joachim Sauer Jun 11 '12 at 12:49
  • 9
    The number of upvotes is a bit distrubing. :] – Peter Lawrey Jun 11 '12 at 12:49
  • ...which it won't be @Joachim, as there would have been a caller. – lotsoffreetime Jun 11 '12 at 12:51
  • @lotsoffreetime: I thought of this, but it could be `newA().someMethod()`. In that case the stack frame on the stack would truly be the only reference. – Joachim Sauer Jun 11 '12 at 12:54
  • 3
    @PeterLawrey: :D I agree. But again, fundamental errors are the worst kind of doubts and its better to ask and weed them out as soon as possible. – Saurabh Agarwal Jun 11 '12 at 12:57
  • 4
    @SaurabhAgarwal: yup, its better to ask then make a mistake! Don't worry about what people say, just hope you learned something here! – Surender Thakran Jun 11 '12 at 13:04
  • @WickeD - *"its better to ask then make a mistake!"*. I'm glad I don't have to mentor you :-). Seriously, it is often better to make the mistake, figure out what it was yourself, and learn from it. Of course, it depends on the nature of the mistake ... but in general, mistakes are not something to be ashamed of provided that you learn from them. – Stephen C Jun 28 '12 at 02:04

14 Answers14

18

You don't "destruct" objects in Java. This is wrong-headed. Don't do it.

Objects are created on the heap in Java. They live as long as there's a reference that points to them. The garbage collector cleans up the mess.

You should certainly do what you can to make sure that you don't accumulate and hold onto references unnecessarily (e.g. Listeners in Swing).

But your proposal is not the right thing at all. Cease and desist.

duffymo
  • 305,152
  • 44
  • 369
  • 561
11
this=null;  //Is this statement valid? Why / Why not?

It is not valid Java because this is not an lvalue; i.e. not something you can assign to. This is a compilation error, just like 42 = i; is a compilation error.

(The JLS says the following about assignments: "The result of the first operand of an assignment operator must be a variable, or a compile-time error occurs." - JLS 15.26.1 The JLS text then goes on to list the different things that qualify as variables, and this is not one of them.)

Besides, as duffymo says, it is a totally wrong-headed thing to do in Java. Just let the GC do its job.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
3

NOTE: What you suggest is highly unlikely to be useful.

What you can do is use delegation.

class A {
   private AImpl impl = new AImpl();

   public void close() {
      if (impl != null)
         impl.close();
      impl = null;
   }
}

As all references are indirect, you can ensure there is only one reference to the real object and clear it.


Proxies in some OSGi containers do this when a component is unloaded. As the container has little control over the lifecycle of the references, it would make it difficult to ever unload a library (the implementation).

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

Your goal is deeply misguided.

Either someone outside the instance holds a non-weak reference to it. Then it will not be collected no matter what you do inside. Or no one does, then it will eventually be collected, no matter what you do inside. In either case, this=null would make no difference, even it were legal java code. Don't do it. If you are concerned about object lifetime and memory exhaustion, look out side the object that you want to get rid of.

Kilian Foth
  • 13,904
  • 5
  • 39
  • 57
1

Setting this = null is like trying to say that an object doesn't reference itself. It always implicitly references itself. You need to find what other objects might be referencing this one and clear their references instead. Usually, this happens automatically because most objects are retained through local variables that are on the stack. When I say "retained" I mean that they are referenced through a chain of references that ultimately leads to a variable on the stack. When you leave the method, the reference is cleared. But if you have a static variable referencing this object that might be a case where you must explicitly set it null.

John Watts
  • 8,717
  • 1
  • 31
  • 35
0

For the java garbage collector to pick up your class it should not be referenced be OTHER classes.

The statement this=null; is illegal because the left hand side of an assignment must be a variable.

tom
  • 2,735
  • 21
  • 35
0

There is no way to explicitly delete the particular reference in Java. Java does this to avoid hanging references. If you delete an object then other objects refer to it can potentially try to access the data and get a reference to invalid data.

You shouldn't be trying to delete objects anyways, just move all references to the object to null.

Hans Z
  • 4,664
  • 2
  • 27
  • 50
0

No. An instance object could be deleted by the GC when no reference points to it, that its, from all running threads could not navigate till the object. When you are in the object executing a method, this method is invoked from outside, so there is a reference to the object. The object itself can not be destroyed, as a reference to it still remains outside.

Consider another approach for memory management.

David Oliván
  • 2,717
  • 1
  • 19
  • 26
0

In methods this is reference to object on which current method is invoked so it should not be possible to changed it. Think of this as final reference.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

Life cycle of objects are ruled by the JVM, due this reason an object cannot decide when itself is no longer needed. What you could do is put some effort on the references to this object. Type of references could be used in order to point the "importance" of the object.

The basic types of references in java can be found here:

More here: http://docs.oracle.com/javase/1.3/docs/api/java/lang/ref/package-summary.html

Discussion about the references here: What is the difference between a soft reference and a weak reference in Java? and Understanding Java's Reference classes: SoftReference, WeakReference, and PhantomReference

Community
  • 1
  • 1
Francisco Spaeth
  • 23,493
  • 7
  • 67
  • 106
0

You can call :

 System.gc() or RuntimeUtil.gc() from the jlibs

but if you do that you mess with the JVM runtime. If you set refernce to null, the object still exists , its just its' reference won't refer to this object and at the next time GC will be invoked it will destroy the object(unless other references refer to it).

David Rasuli
  • 812
  • 4
  • 15
  • 30
0

No the above code is not valid. The reference this of a class only lasts as long as the JVM is being executed. Setting this == null will infact give you a compiler error because though this is termed as reference it is actually a value and you can't assign anything to a value.

Also it is unnecessary since this is valid for only as long as the execution is in that code and GC cannot claim an object which is still executing. However as soon as the execution ends for the object, this will also be lost and the object will automatically become available for GC (i.e. if no other reference to the object exists)

Surender Thakran
  • 3,958
  • 11
  • 47
  • 81
0

This is a compilation error. You cannot assign NULL to 'this'. Keyword 'this' can be used on the right side of equals (with the exception that left hand is not NULL. Reason: nothing can be assigned to null).

For destruction,in java, you have a GC who can do this job for you behind the scenes.

Please note that for user defined objects you can still do something like -

object reference = null;

However 'this' cannot be used on left side of equals.

Ashish K Agarwal
  • 1,172
  • 3
  • 17
  • 33
0

The very reason why the execution thread is inside the destruct() method tells me that there is a caller that is holding a reference to this instance of class A. So, nevertheless, you cant do anything like "this = null" in java - it would not have helped, even though it was allowed in java. You cant destruct to objects in java.