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