Fix findbugs violations in applications
[openflowplugin.git] / applications / forwardingrules-sync / src / main / java / org / opendaylight / openflowplugin / applications / frsync / util / SemaphoreKeeperGuavaImpl.java
index 1a11c9f16fe509eaccfde0df8bada1325db22815..9b485d5e89dbc1d1f35766ad10b989e8512098e9 100644 (file)
@@ -8,22 +8,22 @@
 
 package org.opendaylight.openflowplugin.applications.frsync.util;
 
-import java.util.concurrent.Semaphore;
-
-import javax.annotation.Nonnull;
-
-import org.opendaylight.openflowplugin.applications.frsync.SemaphoreKeeper;
-
+import com.google.common.base.Preconditions;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
+import java.util.Objects;
+import java.util.concurrent.Semaphore;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.opendaylight.openflowplugin.applications.frsync.SemaphoreKeeper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
-/**
- * Key-based semaphore provider.
- */
 public class SemaphoreKeeperGuavaImpl<K> implements SemaphoreKeeper<K> {
 
-    private LoadingCache<K, Semaphore> semaphoreCache;
+    private static final Logger LOG = LoggerFactory.getLogger(SemaphoreKeeperGuavaImpl.class);
+    private final LoadingCache<K, Semaphore> semaphoreCache;
 
     public SemaphoreKeeperGuavaImpl(final int permits, final boolean fair) {
         semaphoreCache = CacheBuilder.newBuilder()
@@ -32,20 +32,32 @@ public class SemaphoreKeeperGuavaImpl<K> implements SemaphoreKeeper<K> {
                 .build(new CacheLoader<K, Semaphore>() {
                     @Override
                     public Semaphore load(final K key) throws Exception {
-                        return new Semaphore(permits, fair) {
-                            private static final long serialVersionUID = 1L;
-                        };
+                        return new Semaphore(permits, fair);
                     }
                 });
     }
 
     @Override
-    public Semaphore summonGuard(final @Nonnull K key) {
+    public Semaphore summonGuard(@Nonnull final K key) {
         return semaphoreCache.getUnchecked(key);
     }
-    
+
+    @Override
+    public Semaphore summonGuardAndAcquire(@Nonnull final K key) {
+        final Semaphore guard = Preconditions.checkNotNull(summonGuard(key), "Guard not available for " + key);
+        try {
+            guard.acquire();
+        } catch (InterruptedException e) {
+            LOG.warn("Could not acquire guard for {}, {}", key, e);
+            return null;
+        }
+        return guard;
+    }
+
     @Override
-    public String toString() {
-        return super.toString() + " size:" + (semaphoreCache == null ? null : semaphoreCache.size()) + " " + semaphoreCache;
+    public void releaseGuard(@Nullable final Semaphore guard) {
+        if (Objects.nonNull(guard)) {
+            guard.release();
+        }
     }
 }