Announcement Announcement Module
Collapse
No announcement yet.
java.lang.reflect.Constructor thread safe ? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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
    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

    Comment


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

      Comment


      • #4
        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

        Comment

        Working...
        X