Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 55203
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 10, 20262026-05-10T17:20:26+00:00 2026-05-10T17:20:26+00:00

In my code, I am creating a collection of objects which will be accessed

  • 0

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 made to insert a new object into my collection, I want to test to see if it is immutable (if not, I’ll throw an exception).

One thing I can do is to check a few well-known immutable types:

private static final Set<Class> knownImmutables = new HashSet<Class>(Arrays.asList(         String.class, Byte.class, Short.class, Integer.class, Long.class,         Float.class, Double.class, Boolean.class, BigInteger.class, BigDecimal.class ));  ...  public static boolean isImmutable(Object o) {     return knownImmutables.contains(o.getClass()); } 

This actually gets me 90% of the way, but sometimes my users will want to create simple immutable types of their own:

public class ImmutableRectangle {     private final int width;     private final int height;     public ImmutableRectangle(int width, int height) {         this.width = width;         this.height = height;     }     public int getWidth() { return width; }     public int getHeight() { return height; } } 

Is there some way (perhaps using reflection) that I could reliably detect whether a class is immutable? False positives (thinking it’s immutable when it isn’t) are not acceptable but false negatives (thinking it’s mutable when it isn’t) are.

Edited to add: Thanks for the insightful and helpful answers. As some of the answers pointed out, I neglected to define my security objectives. The threat here is clueless developers — this is a piece of framework code that will be used by large numbers of people who know next-to-nothing about threading and won’t be reading the documentation. I do NOT need to defend against malicious developers — anyone clever enough to mutate a String or perform other shenanigans will also be smart enough to know it’s not safe in this case. Static analysis of the codebase IS an option, so long as it is automated, but code reviews cannot be counted on because there is no guarantee every review will have threading-savvy reviewers.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-10T17:20:26+00:00Added an answer on May 10, 2026 at 5:20 pm

    There is no reliable way to detect if a class is immutable. This is because there are so many ways a property of a class might be altered and you can’t detect all of them via reflection.

    The only way to get close to this is:

    • Only allow final properties of types that are immutable (primitive types and classes you know are immutable),
    • Require the class to be final itself
    • Require that they inherit from a base class you provide (which is guaranteed to be immutable)

    Then you can check with the following code if the object you have is immutable:

    static boolean isImmutable(Object obj) {     Class<?> objClass = obj.getClass();      // Class of the object must be a direct child class of the required class     Class<?> superClass = objClass.getSuperclass();     if (!Immutable.class.equals(superClass)) {         return false;     }      // Class must be final     if (!Modifier.isFinal(objClass.getModifiers())) {         return false;     }      // Check all fields defined in the class for type and if they are final     Field[] objFields = objClass.getDeclaredFields();     for (int i = 0; i < objFields.length; i++) {         if (!Modifier.isFinal(objFields[i].getModifiers())                 || !isValidFieldType(objFields[i].getType())) {             return false;         }     }      // Lets hope we didn't forget something     return true; }  static boolean isValidFieldType(Class<?> type) {     // Check for all allowed property types...     return type.isPrimitive() || String.class.equals(type); } 

    Update: As suggested in the comments, it could be extended to recurse on the superclass instead of checking for a certain class. It was also suggested to recursively use isImmutable in the isValidFieldType Method. This could probably work and I have also done some testing. But this is not trivial. You can’t just check all field types with a call to isImmutable, because String already fails this test (its field hash is not final!). Also you are easily running into endless recursions, causing StackOverflowErrors 😉 Other problems might be caused by generics, where you also have to check their types for immutablity.

    I think with some work, these potential problems might be solved somehow. But then, you have to ask yourself first if it really is worth it (also performance wise).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 118k
  • Answers 118k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I'm not sure what you mean by "wanting it through… May 11, 2026 at 11:31 pm
  • Editorial Team
    Editorial Team added an answer 1.) I would recommend using the BackgroundWorker instead of separate… May 11, 2026 at 11:31 pm
  • Editorial Team
    Editorial Team added an answer It seems to me that your original two unit tests… May 11, 2026 at 11:31 pm

Related Questions

I am looking for best practices for creating collections made from anonymous types. There
I have a class that handles events from a WinForms control. Based on what
I'm writing an integration test where I will be inserting a number of objects
I am stuck! this seems really daft but I can not see where I

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.