0

In following code snippet, will published object be garbage collected ? Is there any chance that published will stay around as a half constructed object ?

final class Publisher
{
    public static volatile Publisher published;
    public Publisher()
    {
        published = this;
        throw new RuntimeException("Construction not allowed.");
    }
}
Mac
  • 1,711
  • 3
  • 12
  • 26
  • @Sotirios Delimanolis: What exactly is the problem with this question? I went through that link that you have posted but, I couldn't make any guess about any possible answer for my doubt. Can you clarify it? Or, you tell me that what answer you could deduct to this question after reading the link that you have posted in lieu for duplicate . – Mac Jun 26 '14 at 17:17
  • Sure. The first paragraph in the accepted answer explains what happens. `It's possible for the "half-constructed" object to stick around though, if it's made itself visible earlier in the constructor.` That's what happens here. And because that happens, and because the object is reachable through the `static published` reference, the object will not be GC'ed. – Sotirios Delimanolis Jun 26 '14 at 17:22
  • @SotiriosDelimanolis If I make published as final would you still say the same thing? – Mac Jun 26 '14 at 17:24
  • @SotiriosDelimanolis: Ok.. thanks for that. But since `published` is volatile and it would definitely follow happens-before relationship with its volatile read then how is it possible that any one could see the half-initialized `published` object? – Mac Jun 26 '14 at 17:34
  • `volatile` is kind of irrelevant here. The same behavior would occur in a single threaded application. Before the constructor is invoked, memory is allocated to hold the object. Then the constructor is invoked. In your case, it assigns a reference to that memory location to `published` and then terminates by throwing an exception. If outside this call, you then check the value of `published`, you will find a `Publisher` object. – Sotirios Delimanolis Jun 26 '14 at 17:36
  • @SotiriosDelimanolis But the `published` object turns out to be `null` when it is checked outside the constructor .. So my concern is that will this always be case or it might be the case when we will read `published` as half-constructed object? – Mac Jun 26 '14 at 17:40
  • [It won't be `null`.](https://ideone.com/Qql1DC) – Sotirios Delimanolis Jun 26 '14 at 17:43
  • @SotiriosDelimanolis Although in comments but that's great hit as answer. Although I felt a kind of impulsive awkwardness because of you closing my question but My MANY thanks to you for bringing out the answer as such ;). – Mac Jun 26 '14 at 17:51
  • 2
    You're welcome. Note that closing a question as a duplicate is not a bad thing. I upvoted your question because it is interesting, but there was an answer elsewhere. That's all a duplicate is. – Sotirios Delimanolis Jun 26 '14 at 17:53

0 Answers0