5. Don’t Use Static Instance of
SimpleDateFormat
private static final DateFormat dateFormat
= new SimpleDateFormat("yyyy-MM-dd");
…
/* somewhere in the code */
ed =
dateFormat.parse(dateInput.readUTF());
…
/* somewhere in the code */
ed = new SimpleDateFormat("yyyy-MMdd").parse(dateInput.readUTF());
private static final ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>()
{
@Override
protected DateFormat initialValue()
{
return new SimpleDateFormat(“yyyy-MM-dd”);
}
}
…
/* somewhere in the code */
ed = dateFormat.get().parse(dateInput.readUTF());
6. Synchronize Only on Final
private Object mutex = new Object();
private final Object mutex = new Object();
/* somewhere in the code */
synchronized (mutex) {
reload = true;
mutex.notify();
}
/* somewhere in the code */
synchronized (mutex) {
reload = true;
mutex.notify();
}
/* possibly elsewhere in the code */
public void setMutex(Object mutex)
{
this.mutex = mutex;
}
7. Avoid Concatenation While Logging
/* various ways of wrongly using logger */
logger.debug(“Exception = “ + e.getMessage());
logger.debug(“Exception = {}”, e);
logger.debug(“Exception “ + id + “ “ + e.toString());
/* just print the message from exception */
logger.debug(“Exception = {}“, e.getMessage());
/* print the exception stack trace */
logger.debug(“Some Operation”, e);
/* print templatized message with exception stack trace */
logger.debug(“Exception {}“, id, e);
8. Prevent Resource Leak
InputStream stream = new …Stream();
InputStream stream = new …Stream();
while (…) {
try {
process(stream);
while (…) {
}
process(stream);
stream.close();
}
}
finally {
stream.close();
}