Better Locking Performance

Listing 3. Plain synchronized methods create no problem with excessive locking. The object's memory layout is more complex, so construction and garbage collection are slower, extra memory is wasted with object headers and pointers, and additional method invocations are necessary (although inlining usually removes these).

import java.util.Date;

   /**
   * Illustrates a more elegant solution 
   * for locking performance, through 
   * additional encapsulation of the
   * object model.
   */
public class Person2
{
   private final PersonNames names = 
      new PersonNames();
   private final PersonDates dates = 
      new PersonDates();

   /**
   * No locking here anymore.
   */
   public void setNames (
      String name, String surname)
   {
      names.set(name, surname);
   }

   /**
   * No locking here anymore.
   */
   public void setDates (Date birth, Date death)
   {
      dates.set(birth, death);
   }
}

   /**
   * Encapsulates the name information.
   */
class PersonNames
{
   private String name, surname;

   /**
   * Now we can just synchronize the method.
   */
   public synchronized void set (
      String name, String surname)
   {
      this.name = name;
      this.surname = surname;
   }
}

   /**
   * Encapsulates the date information.
   */
class PersonDates
{
   private Date birth, death;
   
   /**
   * Now we can just synchronize the method.
   */
   public synchronized void set (
      Date birth, Date death)
   {
      this.birth = birth;
      this.death = death;
   }
}