Question

I am trying to apply the lessons from reading Java Concurrency In Practice with regards to declaring whether classes that I write are either thread-safe or that they contain unsynchronised mutable state. I think this is a good idea because it documents the intention of how the class should be used.

Today, I wrote a class which wraps an instance of java.lang.Class and java.net.URI. I was about to write in the javadoc that it is thread-safe immutable since both fields were declared as final references. However, I looked at the source code for URI and Class and didn't see any declaration of whether they are thread-safe and it didn't seem immediately obvious.

Thinking about this more generally: is there a list of common java classes stating whether they are thread-safe or not?

On the other had, it probably doesn't matter whether the instances are strictly thread-safe because of the way this class is being used, I will mark it as 'probably thread-safe' for now.

Was it helpful?

Solution

There is no definitive list of thread-safe classes in Java. The only people who could produce a definitive list would be Oracle1, and they haven't done so.


1 - Oracle is the custodian of both the reference Java class libraries (including javadocs), other "official" documentation and .. the official compliance test suite for Java. They are the people who would say whether a class (or subset of a class) that is thread-safe, is thread-safe by design, or whether it is merely a implementation artefact. Nobody else can make that calll with total certainty; i.e. whether a class that is thread-safe in the standard Oracle codebase should also be thread-safe in Harvest / Android codebase or the Classpath codebase, or ...

OTHER TIPS

All immutable classes are assumed to be thread-safe. For mutable classes the common practice is to state explicitly when the class is thread-safe; if nothing is stated, you can't assume thread safety.

I have never heard of a list of thread-safe JDK classes, though.

All java.lang classes (As Marko said immutable classes are assumed to be thread-safe). Also BigDecimal and BigInteger and few more. Unfortunately there is no list of that classes.

If you need some thread-safe collections try Google Guava Immutable Collections (http://code.google.com/p/guava-libraries/wiki/GuavaExplained?tm=6)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top