BUG-139: PCEP capabilities refactor
[bgpcep.git] / pcep / impl / src / main / java / org / opendaylight / protocol / pcep / impl / PeerRecord.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.pcep.impl;
9
10 import com.google.common.cache.Cache;
11 import com.google.common.cache.CacheBuilder;
12 import java.util.concurrent.TimeUnit;
13 import javax.annotation.concurrent.GuardedBy;
14 import javax.annotation.concurrent.ThreadSafe;
15 import org.opendaylight.protocol.util.Values;
16
17 @ThreadSafe
18 final class PeerRecord {
19     @GuardedBy("this")
20     private final Cache<Short, Short> pastIds;
21
22     @GuardedBy("this")
23     private Short lastId;
24
25     PeerRecord(final long idLifetimeSeconds, final Short lastId) {
26         // Note that the cache is limited to 255 entries -- which means we will always have
27         // a single entry available. That number will be the Last Recently Used ID.
28         this.pastIds = CacheBuilder.newBuilder().expireAfterWrite(idLifetimeSeconds, TimeUnit.SECONDS).maximumSize(Values.UNSIGNED_BYTE_MAX_VALUE).build();
29         this.lastId = lastId;
30     }
31
32     synchronized Short allocId() {
33         short id = this.lastId == null ? 0 : this.lastId;
34
35         while (this.pastIds.getIfPresent(id) != null) {
36             id = (short) ((id + 1) % Values.UNSIGNED_BYTE_MAX_VALUE);
37         }
38
39         this.pastIds.put(id, id);
40         this.lastId = id;
41         return id;
42     }
43 }