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;
24 * Key-based semaphore provider.
26 public class SemaphoreKeeperGuavaImpl<K> implements SemaphoreKeeper<K> {
28 private static final Logger LOG = LoggerFactory.getLogger(SemaphoreKeeperGuavaImpl.class);
29 private final LoadingCache<K, Semaphore> semaphoreCache;
31 public SemaphoreKeeperGuavaImpl(final int permits, final boolean fair) {
32 semaphoreCache = CacheBuilder.newBuilder()
35 .build(new CacheLoader<K, Semaphore>() {
37 public Semaphore load(final K key) throws Exception {
38 return new Semaphore(permits, fair) {
39 private static final long serialVersionUID = 1L;
46 public Semaphore summonGuard(@Nonnull final K key) {
47 return semaphoreCache.getUnchecked(key);
51 public Semaphore summonGuardAndAcquire(@Nonnull final K key) {
52 final Semaphore guard = Preconditions.checkNotNull(summonGuard(key), "Guard not available for " + key);
55 } catch (InterruptedException e) {
56 LOG.warn("Could not acquire guard for {}, {}", key, e);
63 public void releaseGuard(@Nullable final Semaphore guard) {
64 if (Objects.nonNull(guard)) {