在Java中,synchronized關鍵字用于控制多個線程對共享資源的訪問,以實現線程同步。然而,當多個線程長時間持有同一個鎖時,可能會導致鎖膨脹,從而影響系統性能。為了避免鎖膨脹,可以采取以下策略:
class FineGrainedLock {
private final Object lock1 = new Object();
private final Object lock2 = new Object();
public void method1() {
synchronized (lock1) {
// ...
}
}
public void method2() {
synchronized (lock2) {
// ...
}
}
}
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
class ReadWriteLockExample {
private final ReadWriteLock lock = new ReentrantReadWriteLock();
public void read() {
lock.readLock().lock();
try {
// ...
} finally {
lock.readLock().unlock();
}
}
public void write() {
lock.writeLock().lock();
try {
// ...
} finally {
lock.writeLock().unlock();
}
}
}
import java.util.concurrent.atomic.AtomicInteger;
class LockFreeExample {
private final AtomicInteger counter = new AtomicInteger(0);
public void increment() {
int oldValue, newValue;
do {
oldValue = counter.get();
newValue = oldValue + 1;
} while (!counter.compareAndSet(oldValue, newValue));
}
}
class ThreadLocalExample {
private static final ThreadLocal<Integer> threadLocalCounter = new ThreadLocal<>();
public void increment() {
int currentValue = threadLocalCounter.getOrDefault(0, 0);
threadLocalCounter.set(currentValue + 1);
}
}
總之,避免鎖膨脹的關鍵是減少線程持有鎖的時間。通過使用細粒度鎖、讀寫鎖、無鎖編程和線程局部變量等方法,可以有效地降低鎖膨脹的風險。