Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
Overcoming Improper Publication in Java

I came across the below class in the book "Java concurrency in practice". The author states that the state of the Holder can be stale in the below example resulting in AssertionError when assertSanity is called. How can the below Holder class be made Immutable to overcome this?

public class Holder{

  private int n;

  public Holder(int n) { this.n = n;}

  public void assertSanity() {
     if(n != n)
          throw new AssertionError(" this statement is false");

  }

}

//unsafe publication
public Holder holder;

public void initialize(){
     holder = new Holder(42);
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

To make the Holder class immutable, simply change

  private int n;

to

  private final int n;

You could also add a public (non-synchronized) getter method for the Holder.n field, if you wanted to. There isn't a lot of point having a private field that nothing can use.

(But get rid of assertSanity because it is of no earthly use.)

When you have done the above, Holder will be immutable with respect to the n field, and you won't have to worry about unsafe publication of that field.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!