Some Java Concurrency Tips
Here is a review of some concurrency tips from Joshua Bloch, Brian
Goetz and others.
Prefer immutable objects/data
Immutable objects do not change after construction. Immutable objects
are simpler, safer, require no locks, and are thread safe. To
make an object immutable don't provide setters/mutator methods, make
fields private final, and prevent subclassing. If immutability is not an option, limit mutable
state, less mutable state means less coordination. Declare fields
final wherever practical, final fields are simpler than mutable fields.
When threads share mutable data, each thread that reads or writes must
coordinate access to the data. Failing to synchronize shared mutable
data can lead to atomicity failures, race conditions, inconsistent
state, and other forms of non-determinism. These erratic problems are among
the most difficult to debug.
Limit concurrent interactions to well defined points, limit shared
data, consider copying instead of sharing.
Threading risks for Web applications
A Servlet get, post, service method can be called for multiple clients at the same
time. Multi-threaded Servlet Instance and Static variables are shared
and therefore if mutable, access must be coordinated. Servlets are
typically long-lived objects with a high thread load, if you
over-synchronize performance suffers, try to either share immutable
(final) data, or don