Skip to content

Commit

Permalink
fun. release write lock
Browse files Browse the repository at this point in the history
  • Loading branch information
symious committed May 7, 2024
1 parent 62f1d26 commit 52e222e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
*/
package org.apache.ratis.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Lock;

Expand All @@ -25,6 +28,7 @@
* so that the {@link #close()} method will unlock the lock.
*/
public final class AutoCloseableLock implements AutoCloseable {
static final Logger LOG = LoggerFactory.getLogger(AutoCloseableLock.class);
/**
* Acquire the given lock and then wrap it with {@link AutoCloseableLock}
* so that the given lock can be released by calling {@link #close()},
Expand All @@ -41,7 +45,14 @@ public static AutoCloseableLock acquire(final Lock lock) {

@SuppressWarnings("java:S2222") // Locks should be release by calling {@link #close()}
public static AutoCloseableLock acquire(final Lock lock, Runnable preUnlock) {
return acquire(lock, preUnlock, false);
}

public static AutoCloseableLock acquire(final Lock lock, Runnable preUnlock, boolean log) {
lock.lock();
if (log) {
LOG.info("Thread: " + Thread.currentThread().getName() + " acquired lock: " + lock);
}
return new AutoCloseableLock(lock, preUnlock);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -393,11 +393,23 @@ public String toString() {
}

public AutoCloseableLock readLock() {
return AutoCloseableLock.acquire(lock.readLock());
Runnable log = new Runnable() {
@Override
public void run() {
LOG.info("Thread " + Thread.currentThread() + " released " + lock.readLock());
}
};
return AutoCloseableLock.acquire(lock.readLock(), log, true);
}

public AutoCloseableLock writeLock() {
return AutoCloseableLock.acquire(lock.writeLock());
Runnable log = new Runnable() {
@Override
public void run() {
LOG.info("Thread " + Thread.currentThread() + " released " + lock.writeLock());
}
};
return AutoCloseableLock.acquire(lock.writeLock(), log, true);
}

public boolean hasWriteLock() {
Expand Down

0 comments on commit 52e222e

Please sign in to comment.