Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1112715
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 17, 20262026-05-17T02:45:09+00:00 2026-05-17T02:45:09+00:00

Read that the following code is an example of unsafe construction as it allows

  • 0

Read that the following code is an example of “unsafe construction” as it allows this reference to escape. I couldn’t quite get how ‘this’ escapes. I am pretty new to the java world. Can any one help me understand this.

public class ThisEscape {
    public ThisEscape(EventSource source) {
        source.registerListener(
            new EventListener() {
                public void onEvent(Event e) {
                    doSomething(e);
                }
            });
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-17T02:45:10+00:00Added an answer on May 17, 2026 at 2:45 am

    The example you have posted in your question comes from “Java Concurrency In Practice” by Brian Goetz et al. It is in section 3.2 “Publication and escape”. I won’t attempt to reproduce the details of that section here. (Go buy a copy for your bookshelf, or borrow a copy from your co-workers!)

    The problem illustrated by the example code is that the constructor allows the reference to the object being constructed to “escape” before the constructor finishes creating the object. This is a problem for two reasons:

    1. 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.

    2. According to JLS 17.5, final attributes of an object can be used safely without synchronization. However, this is only true if the object reference is not published (does not escape) before its constructor finished. If you break this rule, the result is an insidious concurrency bug that might bite you when the code is executed on a multi-core / multi-processor machines.

    The ThisEscape example is sneaky because the reference is escaping via the this reference passed implicitly to the anonymous EventListener class constructor. However, the same problems will arise if the reference is explicitly published too soon.

    Here’s an example to illustrate the problem of incompletely initialized objects:

    public class Thing {
        public Thing (Leaker leaker) {
            leaker.leak(this);
        }
    }
    
    public class NamedThing  extends Thing {
        private String name;
    
        public NamedThing (Leaker leaker, String name) {
            super(leaker);
    
        }
    
        public String getName() {
            return name; 
        }
    }
    

    If the Leaker.leak(...) method calls getName() on the leaked object, it will get null … because at that point in time the object’s constructor chain has not completed.

    Here’s an example to illustrate the unsafe publication problem for final attributes.

    public class Unsafe {
        public final int foo = 42;
        public Unsafe(Unsafe[] leak) {
            leak[0] = this;   // Unsafe publication
            // Make the "window of vulnerability" large
            for (long l = 0; l < /* very large */ ; l++) {
                ...
            }
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            final Unsafe[] leak = new Unsafe[1];
            new Thread(new Runnable() {
                public void run() {
                    Thread.yield();   // (or sleep for a bit)
                    new Unsafe(leak);
                }
            }).start();
    
            while (true) {
                if (leak[0] != null) {
                    if (leak[0].foo == 42) {
                        System.err.println("OK");
                    } else {
                        System.err.println("OUCH!");
                    }
                    System.exit(0);
                }
            }
        }
    }
    

    Some runs of this application may print “OUCH!” instead of “OK”, indicating that the main thread has observed the Unsafe object in an “impossible” state due to unsafe publication via the leak array. Whether this happens or not will depend on your JVM and your hardware platform.

    Now this example is clearly artificial, but it is not difficult to imagine how this kind of thing can happen in real multi-threaded applications.


    The current Java Memory Model was specified in Java 5 (the 3rd edition of the JLS) as a result of JSR 133. Prior to then, memory-related aspects of Java were under-specified. Sources that refer to earlier versions / editions are out of date, but the information on the memory model in Goetz edition 1 is up to date.

    There are some technical aspects of the memory model that are apparently in need of revision; see https://openjdk.java.net/jeps/188 and https://www.infoq.com/articles/The-OpenJDK9-Revised-Java-Memory-Model/. However, this work has yet to appear in a JLS revision.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider the following simple C program that read a file into a buffer and
Following the discussions here on SO I already read several times the remark that
I read that you could call JavaScript code from a Java Applet by calling
I read that Domain Driven Design is about concentrating on the problem domain instead
I read that SQL exceptions are treated as normal exceptions in managed SPs; I
I read that you should define your JavaScript functions in the <head> tag, but
I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I
I once read that one way to obtain a unique filename in a shell
I have read that using database keys in a URL is a bad thing
After having read that QuickSilver was no longer supported by BlackTree and has since

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.