public class Counter {
private int count;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Counter {
private int count;
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
import java.util.concurrent.ConcurrentHashMap;
public class UserCache {
private ConcurrentHashMap<Long, String> cache = new ConcurrentHashMap<>();
public void addUser(Long id, String name) {
cache.put(id, name);
}
public String getNameById(Long id) {
return cache.get(id);
}
}