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.cache.CacheBuilder;
12 import com.google.common.cache.CacheLoader;
13 import com.google.common.cache.LoadingCache;
14 import java.util.concurrent.Semaphore;
15 import javax.annotation.Nonnull;
16 import org.opendaylight.openflowplugin.applications.frsync.SemaphoreKeeper;
19 * Key-based semaphore provider.
21 public class SemaphoreKeeperGuavaImpl<K> implements SemaphoreKeeper<K> {
23 private final LoadingCache<K, Semaphore> semaphoreCache;
25 public SemaphoreKeeperGuavaImpl(final int permits, final boolean fair) {
26 semaphoreCache = CacheBuilder.newBuilder()
29 .build(new CacheLoader<K, Semaphore>() {
31 public Semaphore load(final K key) throws Exception {
32 return new Semaphore(permits, fair) {
33 private static final long serialVersionUID = 1L;
40 public Semaphore summonGuard(final @Nonnull K key) {
41 return semaphoreCache.getUnchecked(key);
45 public String toString() {
46 return super.toString() + " size:" + (semaphoreCache == null ? null : semaphoreCache.size()) + " " + semaphoreCache;