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.Collection;
14 import java.util.EventListener;
16 import java.util.concurrent.ConcurrentHashMap;
17 import java.util.stream.Stream;
18 import org.eclipse.jdt.annotation.NonNull;
19 import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
20 import org.opendaylight.yangtools.concepts.ListenerRegistration;
21 import org.opendaylight.yangtools.concepts.Mutable;
24 * A registry of EventListeners, maintaining a set of registrations. This class is thread-safe.
26 * @param <T> Type of listeners this registry handles
28 public final class ListenerRegistry<T extends EventListener> implements Mutable {
29 private final Set<ListenerRegistration<? extends T>> listeners = ConcurrentHashMap.newKeySet();
30 private final String name;
32 private ListenerRegistry(final String name) {
36 public static <T extends EventListener> @NonNull ListenerRegistry<T> create() {
37 return new ListenerRegistry<>(null);
40 public static <T extends EventListener> @NonNull ListenerRegistry<T> create(final @NonNull String name) {
41 return new ListenerRegistry<>(requireNonNull(name));
45 listeners.stream().forEach(ListenerRegistration::close);
48 public boolean isEmpty() {
49 return listeners.isEmpty();
52 public Stream<? extends T> streamListeners() {
53 return listeners.stream().map(ListenerRegistration::getInstance);
56 public <L extends T> @NonNull ListenerRegistration<L> register(final L listener) {
57 final ListenerRegistration<L> ret = new ListenerRegistrationImpl<>(listener, listeners);
63 public String toString() {
64 return MoreObjects.toStringHelper(this).omitNullValues()
66 .add("size", listeners.size())
70 private static final class ListenerRegistrationImpl<T extends EventListener>
71 extends AbstractListenerRegistration<T> {
72 private Collection<?> removeFrom;
74 ListenerRegistrationImpl(final T instance, final Collection<?> removeFrom) {
76 this.removeFrom = requireNonNull(removeFrom);
80 protected void removeRegistration() {
81 removeFrom.remove(this);
82 // Do not retain reference to that state