blob: 4f6d5b632f5ebb94e30c2200fb10a9b07b353dd8 [file] [log] [blame]
Jordan Halterman948d6592017-04-20 17:18:24 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2017-present Open Networking Foundation
Jordan Halterman948d6592017-04-20 17:18:24 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.store.primitives.impl;
17
18import java.util.Collection;
19import java.util.Map;
20
21import com.google.common.base.MoreObjects;
22import org.onosproject.cluster.PartitionId;
23import org.onosproject.store.service.TransactionalMap;
24
25/**
26 * Partitioned transactional map.
27 */
28public class PartitionedTransactionalMap<K, V> implements TransactionalMap<K, V> {
29 protected final Map<PartitionId, TransactionalMapParticipant<K, V>> partitions;
30 protected final Hasher<K> hasher;
31
32 public PartitionedTransactionalMap(
33 Map<PartitionId, TransactionalMapParticipant<K, V>> partitions, Hasher<K> hasher) {
34 this.partitions = partitions;
35 this.hasher = hasher;
36 }
37
38 /**
39 * Returns the collection of map partitions.
40 *
41 * @return a collection of map partitions
42 */
43 @SuppressWarnings("unchecked")
44 Collection<TransactionParticipant> participants() {
45 return (Collection) partitions.values();
46 }
47
48 /**
49 * Returns the partition for the given key.
50 *
51 * @param key the key for which to return the partition
52 * @return the partition for the given key
53 */
54 private TransactionalMap<K, V> partition(K key) {
55 return partitions.get(hasher.hash(key));
56 }
57
58 @Override
59 public V get(K key) {
60 return partition(key).get(key);
61 }
62
63 @Override
64 public boolean containsKey(K key) {
65 return partition(key).containsKey(key);
66 }
67
68 @Override
69 public V put(K key, V value) {
70 return partition(key).put(key, value);
71 }
72
73 @Override
74 public V remove(K key) {
75 return partition(key).remove(key);
76 }
77
78 @Override
79 public V putIfAbsent(K key, V value) {
80 return partition(key).putIfAbsent(key, value);
81 }
82
83 @Override
84 public boolean remove(K key, V value) {
85 return partition(key).remove(key, value);
86 }
87
88 @Override
89 public boolean replace(K key, V oldValue, V newValue) {
90 return partition(key).replace(key, oldValue, newValue);
91 }
92
93 @Override
94 public String toString() {
95 return MoreObjects.toStringHelper(this)
96 .add("partitions", partitions.values())
97 .toString();
98 }
99}