0

Does an standard static inner builder class which builds an immutable instance of Outer class can be a participant of escape analysis ? Will the instance of static inner class Builder be in stack ?

If for every request this builder.build() is being invoked then i believe every time 2 instances will be created (inner builder and outer class) and will be allocated in heap only and not stack. is my understanding correct ?

Laxmikant
  • 1,551
  • 1
  • 13
  • 30
  • The terms “stack” and “heap” of Java are remotely related to the same terms of languages like `C`, you obviously have in mind, but it is pointless to apply the logic of `C` to Java. In Java, the term “heap” is defined as the memory all objects are allocated from, hence, objects are always allocated on the heap, by definition. And objects are never allocated on the stack, as that wouldn’t improve anything. RAM doesn’t become faster when you call it “stack” instead of “heap”. Scalarization may remove the entire allocation, but whether it happens or not, temporary objects are cheap anyway. – Holger Feb 13 '18 at 08:37
  • @Holger This is not strictly correct. Hot Spot for instance will apply escape analysis and create the object on the stack if it is possible, sometimes allocating just the fields on the stack. – Erik Feb 14 '18 at 13:28
  • @Erik you seem to have fallen for colloquial descriptions of that feature. First, Escape Analysis is only, as its literal meaning suggests, an *analysis*. It’s result enables subsequent optimizations, like Lock Elimination or *Scalarization*. Note that the latter is already mentioned in my previous comment. This optimization decomposes the fields of the local object into individual variables, each of them getting their own treatment. Redundant vars get eliminated completely, some get mapped to CPU registers and others *may* end up on the stack. But this is *not* a stack allocation of an object – Holger Feb 14 '18 at 13:40
  • @Holger What is pertinent is that ea ensures that the object is not allocated on the heap. – Erik Feb 14 '18 at 14:24
  • @Erik as I said in [my first comment](https://stackoverflow.com/questions/48751952/builder-pattern-and-escape-analysis?noredirect=1#comment84525375_48751952): “*Scalarization may remove the entire allocation*”. What is pertinent, is that the linked Q&A does already contain all necessary details, if you want to read more about it. – Holger Feb 14 '18 at 14:35
  • @Holger while I have you the line so to speak, on another question you said that tracing of wide and shallow was faster than deep and narrow of equal size. Do you have a reference to that? I read somewhere someone who measured and couldn't find a difference and I'm interested. – Erik Feb 14 '18 at 14:42

0 Answers0