Skip to content

Instantly share code, notes, and snippets.

@VAlux
Last active April 29, 2022 09:38
Show Gist options
  • Save VAlux/9ae34fe97e216aef7990775ddc1860ef to your computer and use it in GitHub Desktop.
Save VAlux/9ae34fe97e216aef7990775ddc1860ef to your computer and use it in GitHub Desktop.
Thread Safe map wrapper scratch
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.stream.IntStream;
class Scratch {
static class ThreadSafeMap<K, V> {
private final Map<K, V> map = new HashMap<>();
private final ReadWriteLock lock = new ReentrantReadWriteLock();
private final Lock readLock = lock.readLock();
private final Lock writeLock = lock.writeLock();
public void put(final K key, final V value) {
writeLock.lock();
try {
System.out.println("writing " + key + " with " + value);
map.put(key, value);
} finally {
writeLock.unlock();
}
}
public V[] valuesArray(V[] array) {
readLock.lock();
try {
return map.values().toArray(array);
} finally {
readLock.unlock();
}
}
public Collection<V> values() {
readLock.lock();
try {
return new ArrayList<>(map.values());
} finally {
readLock.unlock();
}
}
}
public static void main(String[] args) {
var map = new ThreadSafeMap<Integer, Integer>();
var writeThread = new Thread(() -> {
int counter = 0;
while (true) {
try {
Thread.sleep(10);
counter++;
map.put(counter, counter);
} catch (Exception e) {
System.err.println("Something went wrong in WRITE thread: " + e.getMessage());
e.printStackTrace();
}
}
});
var readThread = new Thread(() -> {
while (true) {
try {
// var sum = Arrays.stream(map.valuesArray(new Integer[]{})).reduce(Integer::sum);
var sum = map.values().stream().reduce(Integer::sum);
System.out.println("Summing values result: " + sum);
Thread.sleep(10);
} catch (Exception e) {
System.err.println("Something went wrong in READ thread: " + e.getMessage());
e.printStackTrace();
}
}
});
readThread.start();
writeThread.start();
System.out.println("Threads started!");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment