0
String hello = new String(new char[]{'H', 'e', 'l', 'l', 'o'});
hello.intern();

I understand that when new operator is being used, hello variable refers to a String object on the heap. In the next line, since it is interned, a new object is created in the String Pool, assuming "Hello" doesn't exist.

In such cases, is the String object on the heap eligible for garbage collection?

I understand that String pool is part of the heap from Java 7 onwards.

jason0x43
  • 3,331
  • 1
  • 13
  • 15
Sara
  • 537
  • 4
  • 14
  • Any object dropped off focus is eligible for garbage collection. – MS90 Dec 23 '18 at 19:02
  • @MS90: What do you mean by "focus"? If you mean "scope" then that's wrong. Objects become eligible for garbage collection when they are *unreachable* by any code that will be executed in the future. – Daniel Pryden Dec 23 '18 at 19:05
  • @Sara: Potentially, *both* objects are eligible for GC, because neither one is referenced afterward. The string pool is not a strong reference, so the string pool alone won't prevent a string from being collected. – Daniel Pryden Dec 23 '18 at 19:08
  • I changed `"Hello"` from constructor argument into `new char[]{'H', 'e', 'l', 'l', 'o'}` to at least give String Pool a chance to not contain `Hello` string. Hope you don't mind. – Pshemo Dec 23 '18 at 19:10
  • @DanielPryden Scope and focus are two different things. Being out of scope doesn't mean being out of focus, but being out of focus means among other things and being out of scope. Garbage collector seeks only object out of focus for collecting. Focus is somehow explained in your second sentence. – MS90 Dec 23 '18 at 19:11
  • 1
    @MS90: The term "focus" is not used by the Java Language Specification, and I've never heard it used before in this context. – Daniel Pryden Dec 23 '18 at 19:17
  • Research community uses it very often, out of focus - a marked object, or more appropriate a memory, ready for sweeping. @DanielPryden – MS90 Dec 23 '18 at 19:30
  • The invocation of `hello.intern()` may also cause the `String` instance referenced by `hello` to be added to the pool, if no string with the same contents existed before. But as @DanielPryden said, the pool is not a strong reference, hence, the string instance would still be eligible to garbage collection. But it’s also possible that another piece of code in the same runtime does a similar call to `intern()` and retrieves exactly that reference, extending the lifetime of the object, before the garbage collector ever ran. – Holger Jan 07 '19 at 15:00

0 Answers0