BUG-113: switch BGP to proper activators
[bgpcep.git] / bgp / parser-spi / src / main / java / org / opendaylight / protocol / bgp / parser / spi / pojo / AbstractFamilyRegistry.java
1 /*
2  * Copyright (c) 2013 Cisco 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.protocol.bgp.parser.spi.pojo;
9
10 import java.util.Map;
11 import java.util.concurrent.ConcurrentHashMap;
12
13 import org.opendaylight.protocol.concepts.AbstractRegistration;
14
15 import com.google.common.base.Preconditions;
16
17 abstract class AbstractFamilyRegistry<CLASS, NUMBER> {
18         private final Map<Class<? extends CLASS>, NUMBER> classToNumber = new ConcurrentHashMap<>();
19         private final Map<NUMBER, Class<? extends CLASS>> numberToClass = new ConcurrentHashMap<>();
20
21         protected synchronized AutoCloseable registerFamily(final Class<? extends CLASS> clazz, final NUMBER number) {
22                 Preconditions.checkNotNull(clazz);
23
24                 final Class<?> c = numberToClass.get(number);
25                 Preconditions.checkState(c == null, "Number " + number + " already registered to " + c);
26
27                 final NUMBER n = classToNumber.get(clazz);
28                 Preconditions.checkState(n == null, "Class " + clazz + " already registered to " + n);
29
30                 numberToClass.put(number, clazz);
31                 classToNumber.put(clazz, number);
32
33                 final Object lock = this;
34                 return new AbstractRegistration() {
35
36                         @Override
37                         protected void removeRegistration() {
38                                 synchronized (lock) {
39                                         classToNumber.remove(clazz);
40                                         numberToClass.remove(number);
41                                 }
42                         }
43                 };
44         }
45
46         protected Class<? extends CLASS> classForFamily(final NUMBER number) {
47                 return numberToClass.get(number);
48         }
49
50         protected NUMBER numberForClass(final Class<? extends CLASS> clazz) {
51                 return classToNumber.get(clazz);
52         }
53 }