For what types variables must never be static?
In one library that is in heavy use in our project there is a restriction that variables of its classes must never be static. (It is ULC). As far as I understood it is because of the need to serialize all of them. And the problem with this rule, is that it is not strict and may be the cause of bugs that are very hard to debug.
We are going to write a module for Checkstyle to detect static variables of such types (detected by some customizable regexp probably). And we need to know how necessary is this check for other developers.
So the question is: What are the general circumstances when variables of some types must never be static开发者_如何学JAVA?
First, proper object oriented design should inform the decision to make a method/field static.
Second, in a web application, where requests are all handled on separate threads, you have to be very careful how you use static methods/fields. If your static method maintains any state across invocations(by using a static field to keep a count, for example), you can run into threading issues. This happens because one request might invoke the static method, and then be stopped in the middle of execution by another thread that invokes the method. If the first invocation modified a common resource, but did not finish, the second invocation might corrupt the progress of the first execution.
Simple answer: a type must never be used as a static instance if it will be modified in a thread-unsafe manner. i suspect this is why the ULC recommends not using their types this way (not because of serialization).
unfortunately, checking this with something like checkstyle is exceedingly difficult. as an example, HashMap is not thread-safe. however, if i construct an instance and populate it staticly during class loading and then only ever read from the map afterwards, this is a safe usage of HashMap (because classloading provides the external thread-safety guarantee on setup and it is never modified afterwards).
精彩评论