Example of ManagedBlocker in Java
December 27, 2013
ManagedBlocker is an interface within the class java.util.concurrent.ForkJoinPool in JDK 7. ManagedBlocker manages the block and release of ForkJoinWorkerThread. ManagedBlocker has two methods, block() and isReleasable(). block() blocks the current thread and isReleasable() method checks if blocking is required. ManagedBlocker can be implemented with the help of ReentrantLock or BlockingQueue and is used by the ForkJoinPool.managedBlock() method in java.
ManagedBlocker using ReentrantLock in Java
Find the code which is displaying how to implement ManagedBlocker using ReentrantLock.Locker.java
package com.concretepage.util.concurrent; import java.util.concurrent.ForkJoinPool.ManagedBlocker; import java.util.concurrent.locks.ReentrantLock; public class Locker implements ManagedBlocker { final ReentrantLock rtlock; boolean isLocked = false; Locker(ReentrantLock rtlock) { this.rtlock = rtlock; } public boolean block() { if (!isLocked){ rtlock.lock(); } return true; } public boolean isReleasable() { return isLocked || (isLocked = rtlock.tryLock()); } }
ManagedBlocker using BlockingQueue in Java
Now look at the code how to implement ManagedBlocker using BlockingQueue.QueueManagedBlocker.java
package com.concretepage.util.concurrent; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ForkJoinPool.ManagedBlocker; public class QueueManagedBlocker<T> implements ManagedBlocker { final BlockingQueue<T> queue; volatile T value = null; QueueManagedBlocker(BlockingQueue<T> queue) { this.queue = queue; } public boolean block() throws InterruptedException { if (value == null) value = queue.take(); return true; } public boolean isReleasable() { return value != null || (value = queue.poll()) != null; } public T getValue() { return value; } }
ForkJoinPool.managedBlock() in Java
ForkJoinPool .ManagedBlocker is used by method ForkJoinPool.managedBlock(). managedBlock() internally calls block() and isReleasable() method to manage block for ForkJoinWorkerThread. Find a sample example of ForkJoinPool.managedBlock() with BlockingQueue.ManagedBlockerDemo.java
package com.concretepage.util.concurrent; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ForkJoinPool; public class ManagedBlockerDemo { public static void main(String[] args) throws InterruptedException { BlockingQueue<String> bq = new ArrayBlockingQueue<String>(2); bq.put("A"); bq.put("B"); QueueManagedBlocker<String> blocker = new QueueManagedBlocker<String>(bq); ForkJoinPool.managedBlock(blocker); System.out.println(blocker.getValue()); } }