Saturday, August 14, 2010

Scalability hints

Avoid lock on static variables or static methods:
It locks your class. Even worse than locking your object!

private static Object myVar = null;
private foo{
    synchronized (myVar){// do not do that
       ....
   }
}
private static synchronized myMethod(){
     .....
}

Use lock free data structures
Use java.util.concurrent.atomic package.It uses lock-free algorithms under the help with hardware synchronization primitives without using native code.

Reduce lock granularity:

Try to prefer  "block locks" instead of "method locks" if possible.synchronized methods locks the Object instance as you know.
public class SchemaManager {
private HashMap schema;
private HashMap treeNodes;
//Bad way!
public boolean synchronized updateSchema(HashMap nodeTree) {
          String nodeName = (String)nodeTree.get("nodeName");
          String nodeAttributes = (List)nodeTree.get("attributes");
          if (nodeName == null)
                  return false;
          else
                  return schema.update(nodeName,nodeAttributes);
}
//Good Way
public boolean updateSchema(HashMap nodeTree) {
String nodeName = (String)nodeTree.get("nodeName");
String nodeAttributes = (List)nodeTree.get("attributes");
synchronized (schema) {
          if (nodeName == null)
                   return false;
          else
                   return schema.update(nodeName,nodeAttributes); }
}
public boolean synchronized updateTreeNodes() { ...... } }


Make synchronized blocks as short as possible
Move the thread safe code outside of the synchronized block.
 
public boolean updateSchema(HashMap nodeTree) {
               synchronized (schema) {
                          String nodeName = (String)nodeTree.get("nodeName");
                          String nodeAttributes = (List)nodeTree.get("attributes");
                          if (nodeName == null)
                                 return false;
                          else
                                 return schema.update(nodeName,nodeAttributes);
                }
}
 
public boolean updateSchema(HashMap nodeTree) {
           String nodeName = (String)nodeTree.get("nodeName");
           String nodeAttributes = (List)nodeTree.get("attributes");
           synchronized (schema) {
                     if (nodeName == null)
                            return false;
                     else
                            return schema.update(nodeName,nodeAttributes);
          }
}




Try to use ThreadLocal variables if possible.

No comments:

Post a Comment