java.util.TimeZone.getTimeZone(id) is a method to obtain a timezone based on an id. While I was using the class I opened it with a decompiler and noticed that it is synchronized. And since it is static, this means that no two threads can invoke the method at the same time. This could be very painful if multiple threads (in a web application for example) are often getting timezones. Why does it have to be synchronized?
Then I realized that the documentation doesn’t say anything about synchronization. So, my decompiler could be wrong. Then I opened the source, and it is synchronized. Why this is not documented? I’m aware that javadoc doesn’t include the synchronized keyword, but it could have been mentioned.
The solution, of course, is to use joda-time DateTimeZone
The method can end up actually creating a
TimeZone(follow the code down) and adding it to aMap. I’m guessing that everyone considered that this isn’t a method you should be calling often and took the easy way out.I’d have difficulty coming up with a legitimate case where this
synchronizedwould be contended. Uncontendedsynchronized(even in really high-performance cases, which is something I work on quite often) is cheap as chips.To get contention, you need not just many threads, but many threads that are hitting this particular block of code at the same time. If you were really having a problem with that in this case, you could easily keep your own cache in a
ConcurrentHashMap, or in an entirely unlocked structure.As to why it’s not documented – synchronization is a property of the implementation. You’d be welcome to implement an alternative library that doesn’t do this synchronization. The JDK docs are documenting the Java libraries, not (for the most part) Sunacle’s implementation thereof.