Add lock to update mCache from the constructor

Without lock, it's not guaranteed that the methods see values
populated by the constructor

Bug: 349952743
Test: TH
(cherry picked from https://android-review.googlesource.com/q/commit:053f9e63e5271be6bb5f10992141cd3c273971b4)
Merged-In: I5c98766a22047f49ad3338bfe620d3b8f4ef477e
Change-Id: I5c98766a22047f49ad3338bfe620d3b8f4ef477e
This commit is contained in:
Motomu Utsumi 2024-07-08 12:10:48 +09:00 committed by Android Build Coastguard Worker
parent 43c04c0cb3
commit 71cfb04dfc

View file

@ -19,6 +19,7 @@ import android.os.Build;
import android.system.ErrnoException;
import android.util.Pair;
import androidx.annotation.GuardedBy;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
@ -60,6 +61,7 @@ import java.util.NoSuchElementException;
public class SingleWriterBpfMap<K extends Struct, V extends Struct> extends BpfMap<K, V> {
// HashMap instead of ArrayMap because it performs better on larger maps, and many maps used in
// our code can contain hundreds of items.
@GuardedBy("this")
private final HashMap<K, V> mCache = new HashMap<>();
// This should only ever be called (hence private) once for a given 'path'.
@ -72,10 +74,12 @@ public class SingleWriterBpfMap<K extends Struct, V extends Struct> extends BpfM
super(path, BPF_F_RDWR_EXCLUSIVE, key, value);
// Populate cache with the current map contents.
K currentKey = super.getFirstKey();
while (currentKey != null) {
mCache.put(currentKey, super.getValue(currentKey));
currentKey = super.getNextKey(currentKey);
synchronized (this) {
K currentKey = super.getFirstKey();
while (currentKey != null) {
mCache.put(currentKey, super.getValue(currentKey));
currentKey = super.getNextKey(currentKey);
}
}
}