ThreadLocal in Java

Recently i needed to implement a thread-safe cache mechanism for SQO-OSS. My first answer was something like that:

public class ThreadSafeCache {
     private Map> maps;

     public ThreadSafeCache() {
           maps = new HashMap>();
     }

     private Map getCurrentCache() {
           Long id = Thread.CurrentThread().getId();
           if(maps.get(id) == null) {
                  maps.put(id, new HashMap());
           }

           return maps.get(id);
     }

     public void addValue(String k, String v) {
           getCurrentCache().put(k, v);
     }
}

This approach worked perfectly. At least it did not crashed for about 160K SQO-OSS jobs :). The problem is that it is actually a hack. Java already provides such mechanism (which i did not know when i wrote that), with the use of ThreadLocal class.

public class ThreadSafeCache {
     private ThreadLocal
> maps; public ThreadSafeCache() { maps = new ThreadLocal >(); maps.set(new HashMap()); } public void addValue(String k, String v) { maps.get().put(k, v); } }

More elegant right? 🙂 I bet that the compiler does a better job for this approach too, in terms of code efficiency and execution speed.

5 things you need to remember when you develop metric plug-ins for SQO-OSS

See a step-by-step tutorial and:

  1. Create the plug-in directory, edit the Makefile and add your plug-in’s directrory to the SUBDIRS variable
  2. Create the pom.xml
  3. If you want to include a jar, put it in the lib directory
  4. If you include jar and want to read resources, add them into your metric plug-in directory
  5. Implement the BundleActivator, AbstractMetric, ProjectVersionMetric, and ProjectFileMetric

For a more solid example, check out metrics directory in the Alitheia repository.

Can Lee!!

I’m coding for SQO-OSS these days, finalizing my contribution (mostly software complexity metrics).

Then i bounced on this piece of code ….. rofl :-p

/**
   * Unused check of the core instance for liveness. Because the instance
   * might not lee without the rest of the bikini services, we need to
   * check that they are present.
   * Added after evening discussion (some 5 pints and a bunch of naked
   * bikini models later) at Amarilia on liveness.
   */
private static boolean canLee(boolean touLiBouDiBouDauTcou) {
   return (null != instance) && touLiBouDiBouDauTcou;
}