BUG-5280: Remove PeristentMessages
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / DelayedListenerRegistration.java
1 /*
2  * Copyright (c) 2015 Brocade Communications 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.cluster.datastore;
9
10 import com.google.common.base.Optional;
11 import java.util.EventListener;
12 import java.util.Map.Entry;
13 import javax.annotation.concurrent.GuardedBy;
14 import org.opendaylight.yangtools.concepts.ListenerRegistration;
15 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
16
17 abstract class DelayedListenerRegistration<L extends EventListener, R> implements ListenerRegistration<L> {
18     private final R registrationMessage;
19     private volatile ListenerRegistration<L> delegate;
20
21     @GuardedBy("this")
22     private boolean closed;
23
24     protected DelayedListenerRegistration(R registrationMessage) {
25         this.registrationMessage = registrationMessage;
26     }
27
28     R getRegistrationMessage() {
29         return registrationMessage;
30     }
31
32     ListenerRegistration<L> getDelegate() {
33         return delegate;
34     }
35
36     synchronized <LR extends ListenerRegistration<L>> void createDelegate(
37             final LeaderLocalDelegateFactory<R, LR, Optional<DataTreeCandidate>> factory) {
38         if (!closed) {
39             final Entry<LR, Optional<DataTreeCandidate>> res = factory.createDelegate(registrationMessage);
40             this.delegate = res.getKey();
41         }
42     }
43
44     @Override
45     public L getInstance() {
46         final ListenerRegistration<L> d = delegate;
47         return d == null ? null : (L)d.getInstance();
48     }
49
50     @Override
51     public synchronized void close() {
52         if (!closed) {
53             closed = true;
54             if (delegate != null) {
55                 delegate.close();
56             }
57         }
58     }
59 }