Class Synchronizer

java.lang.Object
org.apache.wiki.util.Synchronizer

public class Synchronizer extends Object

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
  • Constructor Details

  • Method Details

    • synchronize

      public static <T> T synchronize(ReentrantLock lock, Supplier<T> supplier)
      Executes a given Supplier within a synchronized block managed by a ReentrantLock.

      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.ThrowingRunnable within a synchronized block managed by a ReentrantLock.

      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 synchronization
      throwingRunnable - the ThrowingRunnable to execute