1 // Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 
6 package org.rocksdb;
7 
8 import java.util.*;
9 
10 /**
11  * JNI passthrough for MemoryUtil.
12  */
13 public class MemoryUtil {
14 
15   /**
16    * <p>Returns the approximate memory usage of different types in the input
17    * list of DBs and Cache set.  For instance, in the output map the key
18    * kMemTableTotal will be associated with the memory
19    * usage of all the mem-tables from all the input rocksdb instances.</p>
20    *
21    * <p>Note that for memory usage inside Cache class, we will
22    * only report the usage of the input "cache_set" without
23    * including those Cache usage inside the input list "dbs"
24    * of DBs.</p>
25    *
26    * @param dbs List of dbs to collect memory usage for.
27    * @param caches Set of caches to collect memory usage for.
28    * @return Map from {@link MemoryUsageType} to memory usage as a {@link Long}.
29    */
getApproximateMemoryUsageByType(final List<RocksDB> dbs, final Set<Cache> caches)30   public static Map<MemoryUsageType, Long> getApproximateMemoryUsageByType(final List<RocksDB> dbs, final Set<Cache> caches) {
31     int dbCount = (dbs == null) ? 0 : dbs.size();
32     int cacheCount = (caches == null) ? 0 : caches.size();
33     long[] dbHandles = new long[dbCount];
34     long[] cacheHandles = new long[cacheCount];
35     if (dbCount > 0) {
36       ListIterator<RocksDB> dbIter = dbs.listIterator();
37       while (dbIter.hasNext()) {
38         dbHandles[dbIter.nextIndex()] = dbIter.next().nativeHandle_;
39       }
40     }
41     if (cacheCount > 0) {
42       // NOTE: This index handling is super ugly but I couldn't get a clean way to track both the
43       // index and the iterator simultaneously within a Set.
44       int i = 0;
45       for (Cache cache : caches) {
46         cacheHandles[i] = cache.nativeHandle_;
47         i++;
48       }
49     }
50     Map<Byte, Long> byteOutput = getApproximateMemoryUsageByType(dbHandles, cacheHandles);
51     Map<MemoryUsageType, Long> output = new HashMap<>();
52     for(Map.Entry<Byte, Long> longEntry : byteOutput.entrySet()) {
53       output.put(MemoryUsageType.getMemoryUsageType(longEntry.getKey()), longEntry.getValue());
54     }
55     return output;
56   }
57 
getApproximateMemoryUsageByType(final long[] dbHandles, final long[] cacheHandles)58   private native static Map<Byte, Long> getApproximateMemoryUsageByType(final long[] dbHandles,
59       final long[] cacheHandles);
60 }
61