Java: freeze objects accessible from the final field

Dzone refcard entitled "core Java concurrency" points out:

and

I am not fully aware of the second statement Does this mean that if I have a last field in class a of class B, and the latter has a final field of type integer, what has happened only when the final field of BC is frozen?

public class A{

  public final B b = new B();

}

public class B{ 

  public final Integer c = 10;

}

Solution

I think I'll be careful to say that in this case, the final field freeze means that when you create an instance of a and publish it safely, other objects will never see the uninitialized value of B or C

I will also say that when you create an instance of B in a, other initialization codes in a will never see the uninitialized value of C

An example of a real problem is, for example, a class containing a (variable) HashMap, which is only used to initialize during the construction process:

public class DaysOfWeek {
    private final Map daysOfWeek = new HashMap();
    public DaysOfWeek() { 
      // prepopulate my map
      daysOfWeek.put(0,"Sunday");
      daysOfWeek.put(1,"Monday");
      // etc
    }

    public String getDayName(int dayOfWeek) {
      return daysOfWeek(dayOfWeek);
    }
}

Here's the problem: suppose this object is published safely, and since there is no synchronization here, is it safe for other threads to call getdayname()? The answer is yes, because the final domain freeze ensures that HashMap and everything can reach the structure freeze from it (here is just a string, but it can be any complex object) [if you want to actually modify the map after construction, you need to explicitly synchronize reading and writing.] This is a lengthier blog to explore this topic and check some interesting responses to comments from people like Brian Goetz

BTW I'm the author of refcard

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>