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