[concurrency-interest] Question about "happens-before" and reordering

Robert Kuhar robertkuhar at yahoo.com
Thu May 18 19:57:43 EDT 2006


At a JavaOne session today entitled "Secure Coding Antipatterns:  Avoiding
Vunerabilities" the following code snippet was presented.

  Antipattern 6: Believing a Constructor Exception Destroys the Object
  Problem
    Throwing an exception from a constructor does not prevent a partially
    initialized instance from being acquired
      - Attacker can override finalize method to obtain the object

To solve this problem, they presented the following snippet and explanation:

  Secure Coding Guidelines:
    - If finalize method can be overridden, ensure partially initialized 
      instances are unusable
    - Do not set fields until all checks have completed
    - Use an initialized flag

  public class ClassLoader {
    private boolean initialized = false;
    ClassLoader() {
      securityCheck(); // can throw an Exception
      init();
      initialized = true; // check flag in all relevant methods
    }
  }

I asserted that they had two problems with this code.  As I understand it, the
runtime is free to reorder the instructions in this constructor.  This means
that initialized=true may occur before the calls to either securityCheck() or
init().  If that is the case, its value cannot be trusted as this code stands
now.

Second, even if initialized boolean field gets set correctly, the fact that it
is not covered by any synchronization or volatile means that any thread
(remember, the problem they are trying to solve has to do with malicious
finalizer code) other than the one that new'ed this kid up, may not see the
current value of the initialized boolean field.  Garbage Collection usually
runs on its own thread, no?

It is my opinion that this code is not thread-safe.

The reply was that somehow the Exception that can come out of securityCheck()
establishes some "happens-before" and therefore this code is thread-safe.  I am
skeptical as I have never heard that before (or didn't understand it if I did).

Point by point how right or wrong am I and why.

Thanks.

Bob


__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 


More information about the Concurrency-interest mailing list