Package org.jppf.nio

Class SelectorSynchronizerImpl

java.lang.Object
org.jppf.nio.SelectorSynchronizerImpl
All Implemented Interfaces:
SelectorSynchronizer

public class SelectorSynchronizerImpl extends Object implements SelectorSynchronizer
Synchronization aid for a Selector, to prevent SelectionKey.interestOps(int) invocations from blocking for too long. This implementation synchronizes on itself.

Usage pattern:

- in the selection loop:

 SelectorSynchronizer sync = new SelectorSynchronizerImpl(selector);
 
 try {
   int n = 0;
   while (true) {
     sync.waitForZeroAndSetToMinusOne();
     try {
       n = selector.select(selectTimeout);
     } finally {
       sync.setToZeroIfNegative();
     }
     if (n > 0) {
       // process selected keys
     }
   }
 } catch (Exception e) {
   // process exception
 }
 

- in separate threads:

 public void setInterestOps(SelectionKey key, int newOps) throws Exception {
   sync.wakeUpAndSetOrIncrement();
   try {
     key.interestOps(newOps);
   } finally {
     sync.decrement();
   }
 }
 
Author:
Laurent Cohen
  • Constructor Details

    • SelectorSynchronizerImpl

      public SelectorSynchronizerImpl(Selector selector)
      Initialize with the specified selector.
      Parameters:
      selector - the selector to wakeup.
  • Method Details

    • waitForZeroAndSetToMinusOne

      public void waitForZeroAndSetToMinusOne()
      Wait for the value to go down to zero, then set it to -1.
      Specified by:
      waitForZeroAndSetToMinusOne in interface SelectorSynchronizer
    • setToZeroIfNegative

      public void setToZeroIfNegative()
      Set the value to zero if it is less than 0.
      Specified by:
      setToZeroIfNegative in interface SelectorSynchronizer
    • decrement

      public void decrement()
      Decrement the value.
      Specified by:
      decrement in interface SelectorSynchronizer
    • wakeUpAndSetOrIncrement

      public void wakeUpAndSetOrIncrement()
      Compare the value with the expected value, and run run an action and incrment the value if the comparison succeeds, or set the value to the update value if it does not succeed..
      Specified by:
      wakeUpAndSetOrIncrement in interface SelectorSynchronizer