Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

java - Safe publication through final

Even after going though this, I am still not clear about how usage of final causes safe publication in the below code. Can someone give an easy-to-understand explanation.

public class SafeListener
{
    private final EventListener listener;

    private SafeListener()
    { 
         listener = new EventListener()
         {  public void onEvent(Event e)
            {  doSomething(e); }
          };
    }

    public static SafeListener newInstance(EventSource source)
    {    
          SafeListener safe = new SafeListener(); 
          source.registerListener(safe.listener);
          return safe;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Edited to add: Interesting perspective on the origins of Java and JSR-133's final behavior.

Canonical reference for how final works in the new JMM, for safe publication: http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight

On simple review, I think your code represents "safe" publication to the EventSource source object, which presumably will be fielding event callbacks to listener in a different thread. You are guaranteed that threads operating on the safe.listener reference passed will see a fully-initialized listener field. This does not make any further guarantees about other synchronization issues associated with calls to onEvent or other interactions with the object's state.

What is guaranteed by your code is that, when SafeListener's constructor returns a reference inside the static method, the listener field will not be seen in an unwritten state (even if there is no explicit synchronization). For example: Suppose a thread A calls newInstance(), resulting in an assignment to the listener field. Suppose that a thread B is able to dereference the listener field. Then, even absent any other synchronization, thread B is guaranteed to see the write listener = new EventListener().... If the field were not final, you would not receive that guarantee. There are several (other) ways of providing the guarantee (explicit synchronization, use of an atomic reference, use of volatile) of varying performance and readability.

Not everything that's legal is advisable. Suggest you take a look at JCiP and perhaps this article on safe publication techniques.

A recent, related question is here: "Memory barriers and coding...", "Java multi-threading & Safe Publication".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...