Fix FindBugs error in DelayedListenerRegistration#getInstance
[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         // ObjectRegistration annotates this method as @Nonnull but we could return null if the delegate is not set yet.
43         // In reality, we do not and should not ever call this method on DelayedListenerRegistration instances anyway
44         // but, since we have to provide an implementation to satisfy the interface, we throw
45         // UnsupportedOperationException to honor the API contract of not returning null and to avoid a FindBugs error
46         // for possibly returning null.
47         throw new UnsupportedOperationException(
48                 "getInstance should not be called on this instance since it could be null");
49     }
50
51     @Override
52     public synchronized void close() {
53         if (!closed) {
54             closed = true;
55             if (delegate != null) {
56                 delegate.close();
57             }
58         }
59     }
60 }