Bug 6745 Improve compression queue locking and handle InterruptedException
[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 /**
24  * Key-based semaphore provider.
25  */
26 public class SemaphoreKeeperGuavaImpl<K> implements SemaphoreKeeper<K> {
27
28     private static final Logger LOG = LoggerFactory.getLogger(SemaphoreKeeperGuavaImpl.class);
29     private final LoadingCache<K, Semaphore> semaphoreCache;
30
31     public SemaphoreKeeperGuavaImpl(final int permits, final boolean fair) {
32         semaphoreCache = CacheBuilder.newBuilder()
33                 .concurrencyLevel(1)
34                 .weakValues()
35                 .build(new CacheLoader<K, Semaphore>() {
36                     @Override
37                     public Semaphore load(final K key) throws Exception {
38                         return new Semaphore(permits, fair) {
39                             private static final long serialVersionUID = 1L;
40                         };
41                     }
42                 });
43     }
44
45     @Override
46     public Semaphore summonGuard(@Nonnull final K key) {
47         return semaphoreCache.getUnchecked(key);
48     }
49
50     @Override
51     public Semaphore summonGuardAndAcquire(@Nonnull final K key) {
52         final Semaphore guard = Preconditions.checkNotNull(summonGuard(key), "Guard not available for " + key);
53         try {
54             guard.acquire();
55         } catch (InterruptedException e) {
56             LOG.warn("Could not acquire guard for {}, {}", key, e);
57             return null;
58         }
59         return guard;
60     }
61
62     @Override
63     public void releaseGuard(@Nullable final Semaphore guard) {
64         if (Objects.nonNull(guard)) {
65             guard.release();
66         }
67     }
68 }