Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda