在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);
}
}
总之,避免锁膨胀的关键是减少线程持有锁的时间。通过使用细粒度锁、读写锁、无锁编程和线程局部变量等方法,可以有效地降低锁膨胀的风险。