Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing the this reference to escape

I would appreciate help in understanding the following from 'Java Concurrency in Practice':

Calling an overrideable instance method(one that is neither private nor final) from the constructor can also allow the this reference to escape.

  1. Does 'escape' here simply mean that we may probably be calling an instance method,before the instance is fully constructed?
    I do not see 'this' escaping the scope of the instance in any other way.
  2. How does 'final' prevent this from happening?Is there some aspect of 'final' in instance creation that I am missing?
like image 439
IUnknown Avatar asked Dec 09 '13 15:12

IUnknown


People also ask

What is escaping reference Java?

If the reference escapes, something can use the object before its constructor has completed the initialization and see it in an inconsistent (partly initialized) state. Even if the object escapes after initialization has completed, declaring a subclass can cause this to be violated.


1 Answers

  1. It means calling code outside the class, and passing this.
    That code will assume that the instance is fully initialized, and may break if it isn't.
    Similarly, your class might assume that some methods will only be called after the instance is fully initialized, but the external code is likely to break those assumptions.

  2. final methods cannot be overridden, so you can trust them to not pass this around.
    If you call any non-final method in the constructor for a non-final class, a derived class might override that method and pass this anywhere.
     
    Even when you call final methods, you still need to make sure that they are safely written – that they do not pass this anywhere, and that themselves don't call any non-final methods.

like image 186
SLaks Avatar answered Oct 13 '22 08:10

SLaks