Do JDK classes have any further specifications beyond their Javadoc? If so, where?
For example, consider Collections.unmodifiableMap
. Its Javadoc doesn't say anything about thread-safety; so just going from the Javadoc, I can't assume that it's safe to expose the resulting map to other threads without taking some special steps of my own to gain thread-safety. But IMHO, any realistic implementation would store the internal map in a final
field, so in Java 5 and higher, the resulting map will be thread-safe as long as the internal map is (with a "happens-before" relationship between any accesses of the resulting map and any previous modifications to the internal map). That's what the OpenJDK implementation does, for example.
So, how can I figure out if I can portably assume a given behavior?
The Javadoc is the specification. That said, writing good specification is excruciatingly difficult, balancing both not leaving out useful stuff with not overcommitting (and undermining future ability to evolve implementation.)
If I had to guess, I'd say the reason this was left out of the specification (other than possibly oversight) is that any thread-safety would be conditional than the underlying collection (a) not be published and (b) not be modified after the unmodifiable view is created, and this would have to be carefully specified as well.
In the end there's just a continuum from will never change over could change behavior in the next point release to just happens to work on your platform. Even specified behavior can be deprecated and then removed at some point, it just happens extremely rarely (e.g. Thread.destroy
). So whether you can rely on reasonable-but-unspecified behavior depends how strong a guarantee you need, how much effort you want to spend on coding around things defensively / adding tests to ensure you detect future changes etc.
But yes, the javadocs are the strongest guarantee you can get, everything else means moving onto thinner ice.
Many projects rely on APIs that are not only undocumented but considered internal and ostensibly implementation-specific. sun.misc.Unsafe
being the prime example here, to the point where most of its features became reified as proper JDK APIs in 9.
In the case of Collections.unmodifiableMap
if you wanted to be really defensive about safe publication you could insert a store fence after creating it.