Skip to content
Advertisement

how to understand this interface Executor example in Java API docs [closed]

Can anyone help to explain this piece of code in details?

 class SerialExecutor implements Executor {
   final Queue<Runnable> tasks = new ArrayDeque<Runnable>();
   final Executor executor;
   Runnable active;

   SerialExecutor(Executor executor) {
     this.executor = executor;
   }

   public synchronized void execute(final Runnable r) {
     tasks.offer(new Runnable() {
       public void run() {
         try {
           r.run();
         } finally {
           scheduleNext();
         }
       }
     });
     if (active == null) {
       scheduleNext();
     }
   }

   protected synchronized void scheduleNext() {
     if ((active = tasks.poll()) != null) {
       executor.execute(active);
     }
   }
 }

I am learning java concurrent programming. When i was looking into the piece of code, I feel lost. There are mainly two points confused me:

  1. why define Executor executor inside Executor, how this works?
  2. in public synchronized void execute(final Runnable r) it create new Runnable(){} and in these Runnable, it call Runnable r.run()? what is this?

Advertisement

Answer

  1. why define Executor executor inside Executor, how this works?

The SerialExecutor is a wrapper implementation which uses the decorator pattern. You can instantiate it with any implementation of the Executor interface or you can pass it as an argument where an Executor is expected.

Ex:-

SerialExecutor se = new SerialExecutor(Executors.newFixedThreadPool(10));
Executor anotherExecutor = se;

See the Executors class Java API Documentation for more information

  1. In public synchronized void execute(final Runnable r) it create new Runnable(){} and in these Runnable, it call Runnable r.run()? what is this?

Inside the above method the r.run() is invoked in a new Runnable instance because at the end of calling r.run() in finally block the scheduleNext() method is required to be called.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement