|
| 1 | +/* |
| 2 | + * Licensed to the Apache Software Foundation (ASF) under one |
| 3 | + * or more contributor license agreements. See the NOTICE file |
| 4 | + * distributed with this work for additional information |
| 5 | + * regarding copyright ownership. The ASF licenses this file |
| 6 | + * to you under the Apache License, Version 2.0 (the |
| 7 | + * "License"); you may not use this file except in compliance |
| 8 | + * with the License. You may obtain a copy of the License at |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 12 | + * Unless required by applicable law or agreed to in writing, |
| 13 | + * software distributed under the License is distributed on an |
| 14 | + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | + * KIND, either express or implied. See the License for the |
| 16 | + * specific language governing permissions and limitations |
| 17 | + * under the License. |
| 18 | + */ |
| 19 | + |
| 20 | +package org.apache.samza.table.caching; |
| 21 | + |
| 22 | +import java.util.HashMap; |
| 23 | +import java.util.List; |
| 24 | +import java.util.Map; |
| 25 | +import java.util.concurrent.atomic.AtomicLong; |
| 26 | +import java.util.concurrent.locks.Lock; |
| 27 | + |
| 28 | +import org.apache.samza.container.SamzaContainerContext; |
| 29 | +import org.apache.samza.metrics.MetricsRegistry; |
| 30 | +import org.apache.samza.storage.kv.Entry; |
| 31 | +import org.apache.samza.table.ReadWriteTable; |
| 32 | +import org.apache.samza.table.ReadableTable; |
| 33 | +import org.apache.samza.task.TaskContext; |
| 34 | + |
| 35 | +import com.google.common.base.Preconditions; |
| 36 | +import com.google.common.util.concurrent.Striped; |
| 37 | + |
| 38 | + |
| 39 | +/** |
| 40 | + * A composite table incorporating a cache with a Samza table. The cache is |
| 41 | + * represented as a {@link ReadWriteTable}. |
| 42 | + * |
| 43 | + * The intented use case is to optimize the latency of accessing the actual table, eg. |
| 44 | + * remote tables, when eventual consistency between cache and table is acceptable. |
| 45 | + * The cache is expected to support TTL such that the values can be refreshed at some |
| 46 | + * point. |
| 47 | + * |
| 48 | + * If the actual table is read-write table, CachingTable supports both write-through |
| 49 | + * and write-around (writes bypassing cache) policies. For write-through policy, it |
| 50 | + * supports read-after-write semantics because the value is cached after written to |
| 51 | + * the table. |
| 52 | + * |
| 53 | + * Table and cache are updated (put/delete) in an atomic manner as such it is thread |
| 54 | + * safe for concurrent accesses. Strip locks are used for fine-grained synchronization |
| 55 | + * and the number of stripes is configurable. |
| 56 | + * |
| 57 | + * NOTE: Cache get is not synchronized with put for better parallelism in the read path. |
| 58 | + * As such, cache table implementation is expected to be thread-safe for concurrent |
| 59 | + * accesses. |
| 60 | + * |
| 61 | + * @param <K> type of the table key |
| 62 | + * @param <V> type of the table value |
| 63 | + */ |
| 64 | +public class CachingTable<K, V> implements ReadWriteTable<K, V> { |
| 65 | + private static final String GROUP_NAME = CachingTable.class.getSimpleName(); |
| 66 | + |
| 67 | + private final String tableId; |
| 68 | + private final ReadableTable<K, V> rdTable; |
| 69 | + private final ReadWriteTable<K, V> rwTable; |
| 70 | + private final ReadWriteTable<K, V> cache; |
| 71 | + private final boolean isWriteAround; |
| 72 | + |
| 73 | + // Use stripe based locking to allow parallelism of disjoint keys. |
| 74 | + private final Striped<Lock> stripedLocks; |
| 75 | + |
| 76 | + // Common caching stats |
| 77 | + private AtomicLong hitCount = new AtomicLong(); |
| 78 | + private AtomicLong missCount = new AtomicLong(); |
| 79 | + |
| 80 | + public CachingTable(String tableId, ReadableTable<K, V> table, ReadWriteTable<K, V> cache, int stripes, boolean isWriteAround) { |
| 81 | + this.tableId = tableId; |
| 82 | + this.rdTable = table; |
| 83 | + this.rwTable = table instanceof ReadWriteTable ? (ReadWriteTable) table : null; |
| 84 | + this.cache = cache; |
| 85 | + this.isWriteAround = isWriteAround; |
| 86 | + this.stripedLocks = Striped.lazyWeakLock(stripes); |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * {@inheritDoc} |
| 91 | + */ |
| 92 | + @Override |
| 93 | + public void init(SamzaContainerContext containerContext, TaskContext taskContext) { |
| 94 | + MetricsRegistry metricsRegistry = taskContext.getMetricsRegistry(); |
| 95 | + metricsRegistry.newGauge(GROUP_NAME, new SupplierGauge(tableId + "-hit-rate", () -> hitRate())); |
| 96 | + metricsRegistry.newGauge(GROUP_NAME, new SupplierGauge(tableId + "-miss-rate", () -> missRate())); |
| 97 | + metricsRegistry.newGauge(GROUP_NAME, new SupplierGauge(tableId + "-req-count", () -> requestCount())); |
| 98 | + } |
| 99 | + |
| 100 | + @Override |
| 101 | + public V get(K key) { |
| 102 | + V value = cache.get(key); |
| 103 | + if (value == null) { |
| 104 | + missCount.incrementAndGet(); |
| 105 | + Lock lock = stripedLocks.get(key); |
| 106 | + try { |
| 107 | + lock.lock(); |
| 108 | + if (cache.get(key) == null) { |
| 109 | + // Due to the lack of contains() API in ReadableTable, there is |
| 110 | + // no way to tell whether a null return by cache.get(key) means |
| 111 | + // cache miss or the value is actually null. As such, we cannot |
| 112 | + // support negative cache semantics. |
| 113 | + value = rdTable.get(key); |
| 114 | + if (value != null) { |
| 115 | + cache.put(key, value); |
| 116 | + } |
| 117 | + } |
| 118 | + } finally { |
| 119 | + lock.unlock(); |
| 120 | + } |
| 121 | + } else { |
| 122 | + hitCount.incrementAndGet(); |
| 123 | + } |
| 124 | + return value; |
| 125 | + } |
| 126 | + |
| 127 | + @Override |
| 128 | + public Map<K, V> getAll(List<K> keys) { |
| 129 | + Map<K, V> getAllResult = new HashMap<>(); |
| 130 | + keys.stream().forEach(k -> getAllResult.put(k, get(k))); |
| 131 | + return getAllResult; |
| 132 | + } |
| 133 | + |
| 134 | + @Override |
| 135 | + public void put(K key, V value) { |
| 136 | + Preconditions.checkNotNull(rwTable, "Cannot write to a read-only table: " + rdTable); |
| 137 | + Lock lock = stripedLocks.get(key); |
| 138 | + try { |
| 139 | + lock.lock(); |
| 140 | + rwTable.put(key, value); |
| 141 | + if (!isWriteAround) { |
| 142 | + cache.put(key, value); |
| 143 | + } |
| 144 | + } finally { |
| 145 | + lock.unlock(); |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + @Override |
| 150 | + public void putAll(List<Entry<K, V>> entries) { |
| 151 | + Preconditions.checkNotNull(rwTable, "Cannot write to a read-only table: " + rdTable); |
| 152 | + entries.forEach(e -> put(e.getKey(), e.getValue())); |
| 153 | + } |
| 154 | + |
| 155 | + @Override |
| 156 | + public void delete(K key) { |
| 157 | + Preconditions.checkNotNull(rwTable, "Cannot delete from a read-only table: " + rdTable); |
| 158 | + Lock lock = stripedLocks.get(key); |
| 159 | + try { |
| 160 | + lock.lock(); |
| 161 | + rwTable.delete(key); |
| 162 | + cache.delete(key); |
| 163 | + } finally { |
| 164 | + lock.unlock(); |
| 165 | + } |
| 166 | + } |
| 167 | + |
| 168 | + @Override |
| 169 | + public void deleteAll(List<K> keys) { |
| 170 | + Preconditions.checkNotNull(rwTable, "Cannot delete from a read-only table: " + rdTable); |
| 171 | + keys.stream().forEach(k -> delete(k)); |
| 172 | + } |
| 173 | + |
| 174 | + @Override |
| 175 | + public synchronized void flush() { |
| 176 | + Preconditions.checkNotNull(rwTable, "Cannot flush a read-only table: " + rdTable); |
| 177 | + rwTable.flush(); |
| 178 | + } |
| 179 | + |
| 180 | + @Override |
| 181 | + public void close() { |
| 182 | + this.cache.close(); |
| 183 | + this.rdTable.close(); |
| 184 | + } |
| 185 | + |
| 186 | + double hitRate() { |
| 187 | + long reqs = requestCount(); |
| 188 | + return reqs == 0 ? 1.0 : (double) hitCount.get() / reqs; |
| 189 | + } |
| 190 | + |
| 191 | + double missRate() { |
| 192 | + long reqs = requestCount(); |
| 193 | + return reqs == 0 ? 1.0 : (double) missCount.get() / reqs; |
| 194 | + } |
| 195 | + |
| 196 | + long requestCount() { |
| 197 | + return hitCount.get() + missCount.get(); |
| 198 | + } |
| 199 | +} |
0 commit comments