Replace Preconditions.CheckNotNull per RequireNonNull
[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 static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.Preconditions;
13
14 import java.util.Map;
15 import java.util.concurrent.ConcurrentHashMap;
16
17 import org.opendaylight.protocol.concepts.AbstractRegistration;
18
19 abstract class AbstractFamilyRegistry<C, N> {
20     private final Map<Class<? extends C>, N> classToNumber = new ConcurrentHashMap<>();
21     private final Map<N, Class<? extends C>> numberToClass = new ConcurrentHashMap<>();
22
23     protected synchronized AutoCloseable registerFamily(final Class<? extends C> clazz, final N number) {
24         requireNonNull(clazz);
25
26         final Class<?> c = this.numberToClass.get(number);
27         Preconditions.checkState(c == null, "Number " + number + " already registered to " + c);
28
29         final N n = this.classToNumber.get(clazz);
30         Preconditions.checkState(n == null, "Class " + clazz + " already registered to " + n);
31
32         this.numberToClass.put(number, clazz);
33         this.classToNumber.put(clazz, number);
34
35         final Object lock = this;
36         return new AbstractRegistration() {
37
38             @Override
39             protected void removeRegistration() {
40                 synchronized (lock) {
41                     AbstractFamilyRegistry.this.classToNumber.remove(clazz);
42                     AbstractFamilyRegistry.this.numberToClass.remove(number);
43                 }
44             }
45         };
46     }
47
48     protected Class<? extends C> classForFamily(final N number) {
49         return this.numberToClass.get(number);
50     }
51
52     protected N numberForClass(final Class<? extends C> clazz) {
53         return this.classToNumber.get(clazz);
54     }
55 }