1

A manual I'm reading includes this example, where a ScheduledExecutorService is being created. However, the API shows that ScheduledExecutorService is an interface, not a class. So how is it possible that it is being instantiated?

Here's the sample code shown:

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import static java.util.concurrent.TimeUnit.*;

class BeeperControl {
    private final ScheduledExecutorService scheduler =
            Executors.newScheduledThreadPool(1);

    public void beepForAMinute() {
        final Runnable beeper = new Runnable() {
            public void run() {
                System.out.println("beep");
            }
        };

        final ScheduledFuture<?> future =
                scheduler.scheduleAtFixedRate(beeper, 250, 250, MILLISECONDS);
        scheduler.schedule(
                new Runnable() {
                    public void run() {
                        future.cancel(true);
                    }
                }, 3, SECONDS);
        while (!future.isDone()) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
            }
        }
        scheduler.shutdown();
    }

    public static void main(String[] args) {
        BeeperControl bc = new BeeperControl();
        bc.beepForAMinute();
    }
}
kace91
  • 821
  • 1
  • 10
  • 23

1 Answers1

1

Executors.newSceduledThreadPool(int) is a factory method that returns a class that implements the ScheduledExecutorService interface.

As per GrepCode:

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize, ThreadFactory threadFactory) {
    return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}

So here it is returning the new instance of ScheduledThreadPoolExecutor which implements the ScheduledExecutorService interface.

Timon de Groot
  • 7,255
  • 4
  • 23
  • 38
dkatzel
  • 31,188
  • 3
  • 63
  • 67