2 * Copyright (c) 2014 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
8 package org.opendaylight.controller.md.sal.common.impl.util;
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;
17 import org.opendaylight.yangtools.concepts.Delegator;
19 import com.google.common.base.Preconditions;
21 public class AbstractLockableDelegator<T> implements Delegator<T> {
23 private final ReentrantReadWriteLock delegateLock = new ReentrantReadWriteLock();
24 private final ReadLock delegateReadLock = delegateLock.readLock();
25 private final WriteLock delegateWriteLock = delegateLock.writeLock();
28 protected Lock getDelegateReadLock() {
29 return delegateReadLock;
34 public AbstractLockableDelegator() {
38 public AbstractLockableDelegator(T initialDelegate) {
39 delegate = initialDelegate;
43 public T getDelegate() {
45 delegateReadLock.lock();
48 delegateReadLock.unlock();
52 public T retrieveDelegate() {
54 delegateReadLock.lock();
55 Preconditions.checkState(delegate != null,"Delegate is null");
58 delegateReadLock.unlock();
67 public final T changeDelegate(T newDelegate) {
69 delegateWriteLock.lock();
70 T oldDelegate = delegate;
71 delegate = newDelegate;
72 onDelegateChanged(oldDelegate, newDelegate);
75 delegateWriteLock.unlock();
80 protected void onDelegateChanged(T oldDelegate, T newDelegate) {
81 // NOOP in abstract calss;