Package org.apache.wiki.util
Class Synchronizer
java.lang.Object
org.apache.wiki.util.Synchronizer
Synchronizer Utility Class
This utility class is designed to provide a simplified interface for
executing code blocks in a synchronized manner using ReentrantLock.
It aims to improve code readability and maintainability by abstracting
common locking idioms.
Usage Example:
ReentrantLock lock = new ReentrantLock();
String result = Synchronizer.synchronize(lock, () -> {
// Your synchronized code here
return "some result";
});
- Since:
- 3.0.1
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceSynchronizer.ThrowingRunnable<E extends Exception>Functional interface for runnable tasks that can throw exceptions. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic <T> Tsynchronize(ReentrantLock lock, Supplier<T> supplier) Executes a givenSupplierwithin a synchronized block managed by aReentrantLock.static <E extends Exception>
voidsynchronize(ReentrantLock lock, Synchronizer.ThrowingRunnable<E> throwingRunnable) Executes a givenSynchronizer.ThrowingRunnablewithin a synchronized block managed by aReentrantLock.
-
Constructor Details
-
Synchronizer
public Synchronizer()
-
-
Method Details
-
synchronize
Executes a givenSupplierwithin a synchronized block managed by aReentrantLock.This method acquires the lock, executes the supplier's code, and then releases the lock. It is designed to replace the traditional lock idiom:
lock.lock(); try { doSomething(); } finally { lock.unlock(); }Parameters:
lock- The ReentrantLock to be used for synchronization.supplier- The supplier whose code needs to be executed within the synchronized block.
Returns:
The result produced by the supplier.
Throws:
This method propagates any exceptions thrown by the supplier's code.
- Type Parameters:
T- The type of result produced by the supplier.- Parameters:
lock- The ReentrantLock to be used for synchronization.supplier- The supplier to be executed within the synchronized block.- Returns:
- The result produced by the supplier.
-
synchronize
public static <E extends Exception> void synchronize(ReentrantLock lock, Synchronizer.ThrowingRunnable<E> throwingRunnable) Executes a given
Synchronizer.ThrowingRunnablewithin a synchronized block managed by aReentrantLock.Parameters:
lock- The ReentrantLock to be used for synchronization.throwingRunnable- The ThrowingRunnable whose code needs to be executed within the synchronized block.
Throws:
This method propagates any exceptions thrown by the ThrowingRunnable's code.
- Type Parameters:
E- the type of exception that may be thrown- Parameters:
lock- the ReentrantLock to use for synchronizationthrowingRunnable- the ThrowingRunnable to execute
-