Results 1 to 4 of 4

Thread: java.lang.reflect.Constructor thread safe ?

  1. #1

    Default java.lang.reflect.Constructor thread safe ?

    When you have a Constructor object in Java.
    Is calling the newInstance method on the same Constructor object from multiple threads safe.
    Or is this not thread safe leading to wrongly constructed objects?

  2. #2
    Join Date
    Aug 2004
    Posts
    2,715

    Default

    Though it is not explicitly stated (at least I didn't see) I am sure that Constructor (and also Method) is thread-safe. Semantically there should be no difference in using Constructor.newInstance and in invoking the actual constructor explicitly. The latter approach is in any case thread-safe and so should be the former, too.

    Concerning "wrongly constructed" instances: As stated above, I'm sure that construction itself will not fail due to concurrency. But you have to consider visibility effects. This means, if a reference is made accessible before construction has been finished (e.g. if you publish "this" from inside the constructor) it may happen that another thread might encounter an inconsistent object state. But again, if such thing happens it has nothing to do with using reflection.

    Regards,
    Andreas

  3. #3
    Join Date
    Apr 2006
    Location
    South Carolina
    Posts
    122

    Default

    You would also need to verify that the constructor does not do anything unsafe such as accessing static fields without synchronization.

  4. #4
    Join Date
    Aug 2004
    Posts
    2,715

    Default

    Quote Originally Posted by Bron View Post
    You would also need to verify that the constructor does not do anything unsafe such as accessing static fields without synchronization.
    This is correct, but that is not specific to using reflection. My remarks about thread-safety were not about the actual constructor logic as this does not differ between reflective and programmatic invocation.

    Regards,
    Andreas

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •