0

So in Java if I have two objects of the same type and I set one of them to the other one(both have the same reference) will the garbage collector be called?

ClassName obj1 = new ClassName();
ClassName obj2 = new ClassName();
obj1 = obj2;

Will this call garbage collector? The reason I am asking is because I am making a game for android and I can't have the garbage collector being called while the game is running, as I want the best performance. I know that the "new" keyword will call garbage collection but I don't know if this will. Thanks!

user3843164
  • 369
  • 1
  • 4
  • 14
  • No, the garbage collector is only "called" when measurements in the system indicate it should be. You don't have to worry about when this is. – Hot Licks Jul 31 '14 at 02:45

3 Answers3

3

The constructor ("new" keyword) doesn't call the garbage collector. Once you assign obj2 to obj1, if there are no more references to the original object referred by obj1, the garbage collector can collect it, but you don't know when that would happen.

Eran
  • 387,369
  • 54
  • 702
  • 768
3

Simply unreferencing objects does not force the garbage collector to run. It simply means the object is eligible for collection at some point in the future. There are multiple garbage collection strategies and implementations. Oracle continues to provide new GC strategies through all recent java versions. I am not as familiar with android, but I assume it likely uses even different GC strategies than Oracle.

Brett Okken
  • 6,210
  • 1
  • 19
  • 25
0

The object that obj1 was pointing to will become eligible for garbage collection. You cannot control when the garbage collector is called.

Khary Mendez
  • 1,818
  • 1
  • 14
  • 18
  • You can trigger the garbage collection: [`System.gc()`](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#gc--) – vandale Jul 31 '14 at 02:18
  • This is recognized as a bad practice and generally discouraged. http://stackoverflow.com/questions/2414105/why-is-it-a-bad-practice-to-call-system-gc – Khary Mendez Jul 31 '14 at 02:20
  • Explicitly calling gc() in Android is (or used to be, a couple of years back) required under certain circumstances, to trigger collection of image objects that do not reside in regular heap. But that's one of the few cases where calling gc() is useful. – Hot Licks Jul 31 '14 at 02:47
  • For game development performance is everything and garbage collector will decrease it significantly. Is there any way to sort of 'restrict' the garbage collector to a certain time frame to ensure it doesn't ruin gameplay? – user3843164 Jul 31 '14 at 02:54