How do I identify immutable objects in Java

后端 未结 15 1403
小蘑菇
小蘑菇 2020-11-30 22:40

In my code, I am creating a collection of objects which will be accessed by various threads in a fashion that is only safe if the objects are immutable. When an attempt is m

15条回答
  •  猫巷女王i
    2020-11-30 23:13

    To my knowledge, there is no way to identify immutable objects that is 100% correct. However, I have written a library to get you closer. It performs analysis of bytecode of a class to determine if it is immutable or not, and can execute at runtime. It is on the strict side, so it also allows whitelisting known immutable classes.

    You can check it out at: www.mutabilitydetector.org

    It allows you to write code like this in your application:

    /*
    * Request an analysis of the runtime class, to discover if this
    * instance will be immutable or not.
    */
    AnalysisResult result = analysisSession.resultFor(dottedClassName);
    
    if (result.isImmutable.equals(IMMUTABLE)) {
        /*
        * rest safe in the knowledge the class is
        * immutable, share across threads with joyful abandon
        */
    } else if (result.isImmutable.equals(NOT_IMMUTABLE)) {
        /*
        * be careful here: make defensive copies,
        * don't publish the reference,
        * read Java Concurrency In Practice right away!
        */
    }
    

    It is free and open source under the Apache 2.0 license.

提交回复
热议问题