Fix for Bug 144, Bug 147, 148 - improved codec
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / impl / util / ClassLoaderUtils.java
index 87f31ac5c435820c5ddb5ec505e3dabbab94eba8..6478a03bbc025f8a7fa1f6ec937270a80d807797 100644 (file)
@@ -3,6 +3,7 @@ package org.opendaylight.controller.sal.binding.impl.util;
 
 
 import java.util.concurrent.Callable;
+import java.util.concurrent.locks.Lock;
 
 import static com.google.common.base.Preconditions.*;
 
@@ -10,20 +11,35 @@ import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
 import java.util.ArrayList;
 
+import com.google.common.base.Optional;
+
 public class ClassLoaderUtils {
     
     public static <V> V withClassLoader(ClassLoader cls,Callable<V> function) throws Exception {
-        checkNotNull(cls);
-        checkNotNull(function);
+        return withClassLoaderAndLock(cls, Optional.<Lock>absent(), function);
+    }
+    
+    public static <V> V withClassLoaderAndLock(ClassLoader cls,Lock lock,Callable<V> function) throws Exception {
+        checkNotNull(lock,"Lock should not be null");
+        return withClassLoaderAndLock(cls, Optional.of(lock), function);
+    }
+    
+    public static <V> V withClassLoaderAndLock(ClassLoader cls,Optional<Lock> lock,Callable<V> function) throws Exception {
+        checkNotNull(cls, "Classloader should not be null");
+        checkNotNull(function,"Function should not be null");
+        if(lock.isPresent()) {
+            lock.get().lock();
+        }
         ClassLoader oldCls = Thread.currentThread().getContextClassLoader();
         try {
             Thread.currentThread().setContextClassLoader(cls);
             V result = function.call();
-            Thread.currentThread().setContextClassLoader(oldCls);
             return result;
-        } catch (Exception e) {
+        }  finally {
             Thread.currentThread().setContextClassLoader(oldCls);
-            throw new Exception(e);
+            if(lock.isPresent()) {
+                lock.get().unlock();
+            }
         }
     }