Monday, June 16, 2014

Stinging Lessons Learned Today

  • Don't use static SimpleDateFormat as class member. SimpleDateFormat is not thread safe and multiple threads reaching to a single instance of SimpleDateFormat at the same time may result in strange time formatting results. Use it inside of synchronized block or even better use apache date utils and apache date format those are thread safe and already tested and quality passed solutions :)
  • Know that elements inherited from interface are static although they are not declared as static inside interface.

import java.text.SimpleDateFormat;

public interface MyIntf {
 public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
public class MyImpl implements MyIntf {
 public static void main(String[] args) {
  System.out.println(new MyImpl().dateFormat);

Each MyImpl instance will inherit same dateFormat static instance. It is better not to use object with an interface, just leave it as an interface.
  • To get unique identity of an object, use System.identityHashCode(anObject);

No comments: