2 * Copyright (c) 2013 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.yangtools.util;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.base.MoreObjects;
13 import java.util.Collections;
14 import java.util.EventListener;
16 import java.util.concurrent.ConcurrentHashMap;
17 import java.util.function.Consumer;
18 import java.util.stream.Stream;
19 import org.eclipse.jdt.annotation.NonNull;
20 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
21 import org.opendaylight.yangtools.concepts.ListenerRegistration;
22 import org.opendaylight.yangtools.concepts.Mutable;
25 * A registry of EventListeners, maintaining a set of registrations. This class is thread-safe.
27 * @param <T> Type of listeners this registry handles
29 public final class ListenerRegistry<T extends EventListener> implements Mutable {
31 private final Set<ListenerRegistration<? extends T>> listeners = ConcurrentHashMap.newKeySet();
32 // This conversion is known to be safe.
33 @SuppressWarnings({ "rawtypes", "unchecked" })
34 private final Set<ListenerRegistration<T>> unmodifiableView = (Set) Collections.unmodifiableSet(listeners);
36 private final String name;
38 private ListenerRegistry(final String name) {
42 public static <T extends EventListener> @NonNull ListenerRegistry<T> create() {
43 return new ListenerRegistry<>(null);
46 public static <T extends EventListener> @NonNull ListenerRegistry<T> create(final @NonNull String name) {
47 return new ListenerRegistry<>(requireNonNull(name));
50 public @NonNull Set<? extends ListenerRegistration<? extends T>> getRegistrations() {
51 return unmodifiableView;
54 public boolean isEmpty() {
55 return listeners.isEmpty();
58 public Stream<? extends T> streamListeners() {
59 return listeners.stream().map(ListenerRegistration::getInstance);
62 public <L extends T> @NonNull ListenerRegistration<L> register(final L listener) {
63 final ListenerRegistration<L> ret = new ListenerRegistrationImpl<>(listener, listeners::remove);
69 public String toString() {
70 return MoreObjects.toStringHelper(this).omitNullValues()
72 .add("size", listeners.size())
76 private static final class ListenerRegistrationImpl<T extends EventListener>
77 extends AbstractListenerRegistration<T> {
78 private Consumer<ListenerRegistration<? super T>> removeCall;
80 ListenerRegistrationImpl(final T instance, final Consumer<ListenerRegistration<? super T>> removeCall) {
82 this.removeCall = requireNonNull(removeCall);
86 protected void removeRegistration() {
87 removeCall.accept(this);
88 // Do not retain reference to that state