Bug 7521: Convert byte[] to ShardManagerSnapshot in DatastoreSnapshot
[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 java.util.EventListener;
11 import javax.annotation.concurrent.GuardedBy;
12 import org.opendaylight.yangtools.concepts.ListenerRegistration;
13
14 abstract class DelayedListenerRegistration<L extends EventListener, M> implements ListenerRegistration<L> {
15     private final M registrationMessage;
16     private volatile ListenerRegistration<L> delegate;
17
18     @GuardedBy("this")
19     private boolean closed;
20
21     protected DelayedListenerRegistration(M registrationMessage) {
22         this.registrationMessage = registrationMessage;
23     }
24
25     M getRegistrationMessage() {
26         return registrationMessage;
27     }
28
29     ListenerRegistration<L> getDelegate() {
30         return delegate;
31     }
32
33     synchronized <R extends ListenerRegistration<L>> void createDelegate(
34             final LeaderLocalDelegateFactory<M, R> factory) {
35         if (!closed) {
36             this.delegate = factory.createDelegate(registrationMessage);
37         }
38     }
39
40     @Override
41     public L getInstance() {
42         final ListenerRegistration<L> d = delegate;
43         return d == null ? null : (L)d.getInstance();
44     }
45
46     @Override
47     public synchronized void close() {
48         if (!closed) {
49             closed = true;
50             if (delegate != null) {
51                 delegate.close();
52             }
53         }
54     }
55 }