Posts

Showing posts from April, 2013

Why a synchronized StringBuffer was never a good idea

Introduction StringBuffer is a synchronized class for mutable strings.  The main problem with making it synchronized is that It was usually used as a local variable so making it synchronized just made it slower. It was never a good idea to use it in a multi-threaded way.  This problem is that developers assumed that methods which used StringBuffer were themselves thread safe when they were not. The problem with StringBuffer This is an example from a real class which is used in production in many trading systems. It's not a commonly used but you might assume that StringBuffer gives you thread safety, when it doesn't.     private StringBuffer sb = new StringBuffer();     public void addProperty(String name, String value) {         if (value != null && value.length() > 0) {             if (sb.length() > 0) {                 sb.append(',');             }             sb.append(name).append('=').append( value);         }

Low GC Coding: Efficient listeners (exercise)

Overview There are many ways to implement a listener pattern depending on the assumptions you want to make. This is an exercise to get you thinking about how these can be implemented efficiently. Simple set of listeners Implement a thread safe set of listeners which supports add and remove.  Assume there is *many* more events than add/removes and you want to optimize the notification use case. public interface Observer {     void update(Observable o, Object arg); } public class Observable {     public void addObserver( Observer o) {     }      public   void removeObserver( Observer o) {     }      public   void  notifyObservers(Object arg) {         // must be thread safe         // no locks, no garbage     } } In case you think this is an easy task, note that the built-in Observable uses both a lock and creates lots of garbage. As a part of this task, you should use a set to ignore duplicates, but keep the order Observers were added