4964f14919fa51c006d96dc3ff4308550a34557c
[openflowplugin.git] / applications / forwardingrules-sync / src / main / java / org / opendaylight / openflowplugin / applications / frsync / SemaphoreKeeper.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;
10
11 import java.util.concurrent.Semaphore;
12 import javax.annotation.Nonnull;
13 import javax.annotation.Nullable;
14
15 /**
16  * Proposal for how a key based semaphore provider should look like.
17  * <ul>
18  * <li>thread safe</li>
19  * <li>garbage-collect unused semaphores</li>
20  * <li>for the same key there must be always only one semaphore available</li>
21  * </ul>
22  *
23  *
24  * usage:
25  * <pre>
26  * final Semaphore guard = semaphoreKeeper.summonGuard(key);
27  * guard.acquire();
28  * // guard protected logic ...
29  * guard.release();
30  * </pre>
31  *
32  * @param <K> key type
33  */
34
35 public interface SemaphoreKeeper<K> {
36     /**
37      * @param key semaphore identifier
38      * @return new or existing semaphore for given key, for one key there is always only one semaphore available
39      */
40     Semaphore summonGuard(@Nonnull final K key);
41
42     /**
43      * Get guard and lock for key.
44      * @param key for which guard should be created and acquired
45      * @return semaphore guard
46      */
47     Semaphore summonGuardAndAcquire(@Nonnull final K key);
48
49     /**
50      * Unlock and release guard.
51      * @param guard semaphore guard which should be released
52      */
53     void releaseGuard(@Nullable final Semaphore guard);
54 }