2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.openflowplugin.applications.frsync.util;
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;
23 public class SemaphoreKeeperGuavaImpl<K> implements SemaphoreKeeper<K> {
25 private static final Logger LOG = LoggerFactory.getLogger(SemaphoreKeeperGuavaImpl.class);
26 private final LoadingCache<K, Semaphore> semaphoreCache;
28 public SemaphoreKeeperGuavaImpl(final int permits, final boolean fair) {
29 semaphoreCache = CacheBuilder.newBuilder()
32 .build(new CacheLoader<K, Semaphore>() {
34 public Semaphore load(final K key) throws Exception {
35 return new Semaphore(permits, fair);
41 public Semaphore summonGuard(@Nonnull final K key) {
42 return semaphoreCache.getUnchecked(key);
46 public Semaphore summonGuardAndAcquire(@Nonnull final K key) {
47 final Semaphore guard = Preconditions.checkNotNull(summonGuard(key), "Guard not available for " + key);
50 } catch (InterruptedException e) {
51 LOG.warn("Could not acquire guard for {}", key, e);
58 public void releaseGuard(@Nullable final Semaphore guard) {
59 if (Objects.nonNull(guard)) {