Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 81 additions & 1 deletion java/common/src/main/java/org/apache/tsfile/utils/Binary.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package org.apache.tsfile.utils;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
Expand All @@ -34,9 +35,13 @@ public class Binary implements Comparable<Binary>, Serializable, Accountable {

private static final long INSTANCE_SIZE = shallowSizeOfInstance(Binary.class);
private static final long serialVersionUID = 6394197743397020735L;
private static final long WEAK_REFERENCE_INSTANCE_SIZE =
shallowSizeOfInstance(WeakReference.class);
public static final Binary EMPTY_VALUE = new Binary(new byte[0]);

private byte[] values;
private transient WeakReference<ValuesModificationListener>[] valuesModificationListeners;
private transient int valuesModificationListenerCount;

/** if the bytes v is modified, the modification is visible to this binary. */
public Binary(byte[] v) {
Expand Down Expand Up @@ -120,12 +125,87 @@ public byte[] getValues() {
return values;
}

@SuppressWarnings("unchecked")
public synchronized void addValuesModificationListener(ValuesModificationListener listener) {
if (listener == null) {
throw new NullPointerException("listener");
}
compactValuesModificationListeners();
for (int i = 0; i < valuesModificationListenerCount; i++) {
if (valuesModificationListeners[i].get() == listener) {
return;
}
}
if (valuesModificationListeners == null) {
valuesModificationListeners = new WeakReference[1];
} else if (valuesModificationListenerCount == valuesModificationListeners.length) {
valuesModificationListeners =
Arrays.copyOf(valuesModificationListeners, valuesModificationListeners.length * 2);
}
valuesModificationListeners[valuesModificationListenerCount++] = new WeakReference<>(listener);
}

private synchronized ValuesModificationListener[] getValuesModificationListeners() {
if (valuesModificationListeners == null) {
return null;
}
ValuesModificationListener[] activeListeners =
new ValuesModificationListener[valuesModificationListenerCount];
int activeCount = 0;
for (int i = 0; i < valuesModificationListenerCount; i++) {
WeakReference<ValuesModificationListener> reference = valuesModificationListeners[i];
ValuesModificationListener listener = reference.get();
if (listener != null) {
valuesModificationListeners[activeCount] = reference;
activeListeners[activeCount++] = listener;
}
}
Arrays.fill(valuesModificationListeners, activeCount, valuesModificationListenerCount, null);
valuesModificationListenerCount = activeCount;
return activeCount == 0 ? null : Arrays.copyOf(activeListeners, activeCount);
}

private void compactValuesModificationListeners() {
if (valuesModificationListeners == null) {
return;
}
int activeCount = 0;
for (int i = 0; i < valuesModificationListenerCount; i++) {
WeakReference<ValuesModificationListener> reference = valuesModificationListeners[i];
if (reference.get() != null) {
valuesModificationListeners[activeCount++] = reference;
}
}
Arrays.fill(valuesModificationListeners, activeCount, valuesModificationListenerCount, null);
valuesModificationListenerCount = activeCount;
}

public void setValues(byte[] values) {
if (this.values == values) {
return;
}
this.values = values;
ValuesModificationListener[] listeners = getValuesModificationListeners();
if (listeners != null) {
for (ValuesModificationListener listener : listeners) {
listener.onValuesModified(this);
}
}
}

public interface ValuesModificationListener {
void onValuesModified(Binary binary);
}

@Override
public long ramBytesUsed() {
return INSTANCE_SIZE + sizeOf(values);
synchronized (this) {
long retainedSize = INSTANCE_SIZE + sizeOf(values);
if (valuesModificationListeners != null) {
retainedSize += RamUsageEstimator.shallowSizeOf(valuesModificationListeners);
retainedSize += valuesModificationListenerCount * WEAK_REFERENCE_INSTANCE_SIZE;
}
return retainedSize;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,11 @@
SIZE_OF_ARRAYLIST = RamUsageEstimator.shallowSizeOfInstance(ArrayList.class);
}

public static final int INTEGER_CACHE_MIN_VALUE = -128;
public static final int INTEGER_CACHE_MAX_VALUE;

/** JVMs typically cache small longs. This tries to find out what the range is. */
static final long LONG_CACHE_MIN_VALUE, LONG_CACHE_MAX_VALUE;
public static final long LONG_CACHE_MIN_VALUE, LONG_CACHE_MAX_VALUE;

static final int LONG_SIZE, STRING_SIZE;

Expand Down Expand Up @@ -199,6 +202,8 @@
// Object header + BitMap.implementation (reference).
BIT_MAP_SIZE = alignObjectSize((long) NUM_BYTES_OBJECT_HEADER + NUM_BYTES_OBJECT_REF);

INTEGER_CACHE_MAX_VALUE = getIntegerCacheMaxValue();

// get min/max value of cached Long class instances:
long longCacheMinValue = 0;
while (longCacheMinValue > Long.MIN_VALUE && isCachedLong(longCacheMinValue - 1)) {
Expand All @@ -214,6 +219,29 @@
STRING_SIZE = (int) shallowSizeOfInstance(String.class);
}

private static int getIntegerCacheMaxValue() {
int lowerBound = 127;
long upperBound = 128;
while (upperBound < Integer.MAX_VALUE
&& Integer.valueOf((int) upperBound) == Integer.valueOf((int) upperBound)) {
lowerBound = (int) upperBound;
upperBound = Math.min((long) Integer.MAX_VALUE, upperBound * 2);
}
if (upperBound == Integer.MAX_VALUE
&& Integer.valueOf(Integer.MAX_VALUE) == Integer.valueOf(Integer.MAX_VALUE)) {
return Integer.MAX_VALUE;
}
while (upperBound - lowerBound > 1) {
int middle = (int) (lowerBound + (upperBound - lowerBound) / 2);
if (Integer.valueOf(middle) == Integer.valueOf(middle)) {
lowerBound = middle;
} else {
upperBound = middle;
}
}
return lowerBound;
}

/** Approximate memory usage that we assign to a Hashtable / HashMap entry. */
public static final long HASHTABLE_RAM_BYTES_PER_ENTRY =
2
Expand Down Expand Up @@ -586,7 +614,7 @@
// Walk type hierarchy
for (; clazz != null; clazz = clazz.getSuperclass()) {
final Field[] fields =
AccessController.doPrivileged((PrivilegedAction<Field[]>) clazz::getDeclaredFields);

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / unit-test (17, macos-latest)

java.security.AccessController in java.security has been deprecated and marked for removal

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / Generate java fixtures (shard 0)

java.security.AccessController in java.security has been deprecated and marked for removal

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / Generate java fixtures (shard 1)

java.security.AccessController in java.security has been deprecated and marked for removal

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / Generate java fixtures (shard 2)

java.security.AccessController in java.security has been deprecated and marked for removal

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / unit-test (25, ubuntu-latest)

java.security.AccessController in java.security has been deprecated and marked for removal

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / unit-test (21, ubuntu-latest)

java.security.AccessController in java.security has been deprecated and marked for removal

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / unit-test (25, macos-latest)

java.security.AccessController in java.security has been deprecated and marked for removal

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / unit-test (17, ubuntu-latest)

java.security.AccessController in java.security has been deprecated and marked for removal

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / unit-test (21, macos-latest)

java.security.AccessController in java.security has been deprecated and marked for removal

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / Validate cpp shard 1 with java

java.security.AccessController in java.security has been deprecated and marked for removal

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / Validate cpp shard 0 with java

java.security.AccessController in java.security has been deprecated and marked for removal

Check warning on line 617 in java/common/src/main/java/org/apache/tsfile/utils/RamUsageEstimator.java

View workflow job for this annotation

GitHub Actions / Validate cpp shard 2 with java

java.security.AccessController in java.security has been deprecated and marked for removal
for (Field f : fields) {
if (!Modifier.isStatic(f.getModifiers())) {
size = adjustForField(size, f);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

import org.apache.tsfile.file.metadata.enums.TSEncoding;
import org.apache.tsfile.i18n.Messages;
import org.apache.tsfile.utils.RamUsageEstimator;
import org.apache.tsfile.utils.ReadWriteForEncodingUtils;

import org.slf4j.Logger;
Expand Down Expand Up @@ -52,10 +53,16 @@
public class BitmapEncoder extends Encoder {

private static final Logger logger = LoggerFactory.getLogger(BitmapEncoder.class);
private static final long BOXED_VALUE_SIZE =
RamUsageEstimator.shallowSizeOfInstance(Integer.class);

/** Bitmap Encoder stores all current values in a list temporally. */
private List<Integer> values;

private int maximumValuesSize;

private long currentValuesRetainedSize;

/** BitmapEncoder constructor. */
public BitmapEncoder() {
super(TSEncoding.BITMAP);
Expand All @@ -76,6 +83,11 @@ public BitmapEncoder() {
@Override
public void encode(int value, ByteArrayOutputStream out) {
values.add(value);
maximumValuesSize = Math.max(maximumValuesSize, values.size());
if (value < RamUsageEstimator.INTEGER_CACHE_MIN_VALUE
|| value > RamUsageEstimator.INTEGER_CACHE_MAX_VALUE) {
currentValuesRetainedSize += BOXED_VALUE_SIZE;
}
}

/**
Expand Down Expand Up @@ -117,6 +129,7 @@ public void flush(ByteArrayOutputStream out) throws IOException {

private void reset() {
values.clear();
currentValuesRetainedSize = 0;
}

@Override
Expand All @@ -129,4 +142,10 @@ public long getMaxByteSize() {
// byteCacheSize + byteDictSize + (byte array + array length) * byteDictSize
return (long) 4 + 4 + ((values.size() + 7L) / 8 + 4) * values.size();
}

@Override
public long getRetainedSizeInBytes() {
return RamUsageEstimator.shallowSizeOf(this)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May cache the shallow size if it is static.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The boxed Integer shallow size is already cached in the static final BOXED_VALUE_SIZE field, initialized once when the class loads, so no further change was needed.

+ estimateArrayListRetainedSize(maximumValuesSize, currentValuesRetainedSize);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@

import org.apache.tsfile.common.bitStream.BitOutputStream;
import org.apache.tsfile.file.metadata.enums.TSEncoding;
import org.apache.tsfile.utils.PublicBAOS;
import org.apache.tsfile.utils.RamUsageEstimator;
import org.apache.tsfile.utils.ReadWriteForEncodingUtils;

import java.io.ByteArrayOutputStream;
Expand Down Expand Up @@ -51,7 +53,7 @@ public class CamelEncoder extends Encoder {
public static final long[] threshold = new long[DECIMAL_MAX_COUNT];

private final BitOutputStream out;
private final ByteArrayOutputStream baos = new ByteArrayOutputStream();
private final PublicBAOS baos = new PublicBAOS();

static {
for (int l = 1; l <= DECIMAL_MAX_COUNT; l++) {
Expand Down Expand Up @@ -131,6 +133,15 @@ public long getMaxByteSize() {
return 1 + this.baos.size() + 8 + 8;
}

@Override
public long getRetainedSizeInBytes() {
return RamUsageEstimator.shallowSizeOf(this)
+ RamUsageEstimator.shallowSizeOf(baos)
+ RamUsageEstimator.sizeOf(baos.getBuf())
+ RamUsageEstimator.shallowSizeOf(out)
+ RamUsageEstimator.shallowSizeOf(gorillaEncoder);
}

public class GorillaEncoder {
private int leadingZeros = Integer.MAX_VALUE;
private int trailingZeros = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.apache.tsfile.file.metadata.enums.TSEncoding;
import org.apache.tsfile.i18n.Messages;
import org.apache.tsfile.utils.BytesUtils;
import org.apache.tsfile.utils.RamUsageEstimator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -66,6 +67,11 @@ protected DeltaBinaryEncoder(int size) {
blockSize = size;
}

@Override
public long getRetainedSizeInBytes() {
return RamUsageEstimator.shallowSizeOf(this) + RamUsageEstimator.sizeOf(encodingBlockBuffer);
}

protected abstract void writeHeader() throws IOException;

protected abstract void writeValueToBytes(int i);
Expand Down Expand Up @@ -238,6 +244,11 @@ public long getMaxByteSize() {
// The meaning of 24 is: index(4)+width(4)+minDeltaBase(4)+firstValue(4)
return (long) 24 + (long) writeIndex * 4;
}

@Override
public long getRetainedSizeInBytes() {
return super.getRetainedSizeInBytes() + RamUsageEstimator.sizeOf(deltaBlockBuffer);
}
}

public static class LongDeltaEncoder extends DeltaBinaryEncoder {
Expand Down Expand Up @@ -310,6 +321,11 @@ public long getMaxByteSize() {
return (long) 24 + (long) writeIndex * 8;
}

@Override
public long getRetainedSizeInBytes() {
return super.getRetainedSizeInBytes() + RamUsageEstimator.sizeOf(deltaBlockBuffer);
}

/**
* input a integer or long value.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import org.apache.tsfile.file.metadata.enums.TSEncoding;
import org.apache.tsfile.i18n.Messages;
import org.apache.tsfile.utils.Binary;
import org.apache.tsfile.utils.RamUsageEstimator;
import org.apache.tsfile.utils.ReadWriteForEncodingUtils;

import org.slf4j.Logger;
Expand All @@ -44,12 +45,17 @@
* }</pre>
*/
public class DictionaryEncoder extends Encoder {

private static final long BOXED_INDEX_SIZE =
RamUsageEstimator.shallowSizeOfInstance(Integer.class);
private static final Logger logger = LoggerFactory.getLogger(DictionaryEncoder.class);

private HashMap<Binary, Integer> entryIndex;
private List<Binary> indexEntry;
private IntRleEncoder valuesEncoder;
private long mapSize;
private long dictionaryEntriesRetainedSize;
private int maximumDictionarySize;

public DictionaryEncoder() {
super(TSEncoding.DICTIONARY);
Expand All @@ -66,9 +72,15 @@ public void encode(Binary value, ByteArrayOutputStream out) {
entryIndex.computeIfAbsent(
value,
v -> {
int index = indexEntry.size();
indexEntry.add(v);
mapSize += v.getLength();
return entryIndex.size();
dictionaryEntriesRetainedSize += v.ramBytesUsed();
if (index > RamUsageEstimator.INTEGER_CACHE_MAX_VALUE) {
dictionaryEntriesRetainedSize += BOXED_INDEX_SIZE;
}
maximumDictionarySize = Math.max(maximumDictionarySize, indexEntry.size());
return index;
});
valuesEncoder.encode(i, out);
}
Expand Down Expand Up @@ -96,6 +108,28 @@ public long getMaxByteSize() {
return 4 + mapSize + valuesEncoder.getMaxByteSize();
}

@Override
public long getRetainedSizeInBytes() {
return RamUsageEstimator.shallowSizeOf(this)
+ RamUsageEstimator.shallowSizeOf(entryIndex)
+ (long) entryIndex.size() * RamUsageEstimator.SHALLOW_SIZE_OF_HASHMAP_ENTRY
+ dictionaryEntriesRetainedSize
+ estimateHashMapTableSize(maximumDictionarySize)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

major java/tsfile/src/main/java/org/apache/tsfile/encoding/encoder/DictionaryEncoder.java:117 — HashMap table size estimated from stale maximumDictionarySize

maximumDictionarySize is only updated inside the computeIfAbsent lambda, i.e. only when a new entry is inserted. After reset() the map is cleared but maximumDictionarySize keeps the previous peak, so estimateHashMapTableSize(maximumDictionarySize) reports a full-size table for an empty map; conversely, while entries are being added the value lags by one insert. Trigger: encode N distinct values, flush, then call getRetainedSizeInBytes() — the estimate still charges a table sized for
…[truncated]

Fix: Base the table estimate on the live map (entryIndex.size()), or reset maximumDictionarySize in reset() and update it before/after insertion outside the lambda.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion. No change is needed: maximumDictionarySize is updated after indexEntry.add(v), and HashMap.clear()/ArrayList.clear() retain their backing arrays. Keeping the peak is necessary to estimate capacity after reset; using the live map size would undercount it.

+ estimateArrayListRetainedSize(maximumDictionarySize, 0)
+ valuesEncoder.getRetainedSizeInBytes();
}

private long estimateHashMapTableSize(int size) {
if (size == 0) {
return 0;
}
int capacity = 16;
while ((long) size > (long) capacity * 3 / 4 && capacity < (1 << 30)) {
capacity <<= 1;
}
return RamUsageEstimator.sizeOfObjectArray(capacity);
}

private void writeMap(ByteArrayOutputStream out) throws IOException {
ReadWriteForEncodingUtils.writeVarInt(indexEntry.size(), out);
for (Binary value : indexEntry) {
Expand All @@ -113,5 +147,6 @@ private void reset() {
indexEntry.clear();
valuesEncoder.reset();
mapSize = 0;
dictionaryEntriesRetainedSize = 0;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.apache.tsfile.encoding.fire.LongFire;
import org.apache.tsfile.exception.encoding.TsFileEncodingException;
import org.apache.tsfile.i18n.Messages;
import org.apache.tsfile.utils.RamUsageEstimator;
import org.apache.tsfile.utils.ReadWriteForEncodingUtils;

import java.io.ByteArrayOutputStream;
Expand Down Expand Up @@ -66,6 +67,15 @@ public long getMaxByteSize() {
return 1 + (long) (values.size() + 1) * Double.BYTES;
}

@Override
public long getRetainedSizeInBytes() {
return super.getRetainedSizeInBytes()
+ getVectorRetainedSize(values, Double.class)
+ RamUsageEstimator.sizeOf(convertBuffer)
+ (firePred == null ? 0 : firePred.getRetainedSizeInBytes())
+ RamUsageEstimator.shallowSizeOf(packer);
}

protected long predict(Double value, Double preVlaue) throws TsFileEncodingException {
long pred;
if (predictMethod.equals("delta")) {
Expand Down
Loading
Loading