Fix findbugs violations in applications
[openflowplugin.git] / applications / forwardingrules-sync / src / main / java / org / opendaylight / openflowplugin / applications / frsync / util / SemaphoreKeeperGuavaImpl.java
1 /**
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.openflowplugin.applications.frsync.util;
10
11 import com.google.common.base.Preconditions;
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import java.util.Objects;
16 import java.util.concurrent.Semaphore;
17 import javax.annotation.Nonnull;
18 import javax.annotation.Nullable;
19 import org.opendaylight.openflowplugin.applications.frsync.SemaphoreKeeper;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 public class SemaphoreKeeperGuavaImpl<K> implements SemaphoreKeeper<K> {
24
25     private static final Logger LOG = LoggerFactory.getLogger(SemaphoreKeeperGuavaImpl.class);
26     private final LoadingCache<K, Semaphore> semaphoreCache;
27
28     public SemaphoreKeeperGuavaImpl(final int permits, final boolean fair) {
29         semaphoreCache = CacheBuilder.newBuilder()
30                 .concurrencyLevel(1)
31                 .weakValues()
32                 .build(new CacheLoader<K, Semaphore>() {
33                     @Override
34                     public Semaphore load(final K key) throws Exception {
35                         return new Semaphore(permits, fair);
36                     }
37                 });
38     }
39
40     @Override
41     public Semaphore summonGuard(@Nonnull final K key) {
42         return semaphoreCache.getUnchecked(key);
43     }
44
45     @Override
46     public Semaphore summonGuardAndAcquire(@Nonnull final K key) {
47         final Semaphore guard = Preconditions.checkNotNull(summonGuard(key), "Guard not available for " + key);
48         try {
49             guard.acquire();
50         } catch (InterruptedException e) {
51             LOG.warn("Could not acquire guard for {}, {}", key, e);
52             return null;
53         }
54         return guard;
55     }
56
57     @Override
58     public void releaseGuard(@Nullable final Semaphore guard) {
59         if (Objects.nonNull(guard)) {
60             guard.release();
61         }
62     }
63 }