Merge "Fix warnings reported in toaster"
[controller.git] / opendaylight / md-sal / sal-common-impl / src / main / java / org / opendaylight / controller / md / sal / common / impl / util / AbstractLockableDelegator.java
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.controller.md.sal.common.impl.util;
9
10 import java.util.concurrent.locks.Lock;
11 import java.util.concurrent.locks.ReentrantReadWriteLock;
12 import java.util.concurrent.locks.ReentrantReadWriteLock.ReadLock;
13 import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
14
15 import org.opendaylight.yangtools.concepts.Delegator;
16
17 import com.google.common.base.Preconditions;
18
19 public class AbstractLockableDelegator<T> implements Delegator<T> {
20
21     private final ReentrantReadWriteLock delegateLock = new ReentrantReadWriteLock();
22     private final ReadLock delegateReadLock = delegateLock.readLock();
23     private final WriteLock delegateWriteLock = delegateLock.writeLock();
24
25
26     protected Lock getDelegateReadLock() {
27         return delegateReadLock;
28     }
29
30     private T delegate;
31
32     public AbstractLockableDelegator() {
33         // NOOP
34     }
35
36     public AbstractLockableDelegator(T initialDelegate) {
37         delegate = initialDelegate;
38     }
39
40     @Override
41     public T getDelegate() {
42         try {
43             delegateReadLock.lock();
44             return delegate;
45         } finally {
46             delegateReadLock.unlock();
47         }
48     }
49
50     public T retrieveDelegate() {
51         try {
52             delegateReadLock.lock();
53             Preconditions.checkState(delegate != null,"Delegate is null");
54             return delegate;
55         } finally {
56             delegateReadLock.unlock();
57         }
58     }
59
60     /**
61      *
62      * @param newDelegate
63      * @return oldDelegate
64      */
65     public final T changeDelegate(T newDelegate) {
66         try {
67             delegateWriteLock.lock();
68             T oldDelegate = delegate;
69             delegate = newDelegate;
70             onDelegateChanged(oldDelegate, newDelegate);
71             return oldDelegate;
72         } finally {
73             delegateWriteLock.unlock();
74         }
75     }
76
77
78     protected void onDelegateChanged(T oldDelegate, T newDelegate) {
79         // NOOP in abstract calss;
80     }
81 }