package net.openhft.chronicle.core.threads;

import java.util.function.Supplier;

public class OnDemandEventLoop implements EventLoop {
    private final Supplier<EventLoop> eventLoopSupplier;
    private volatile EventLoop eventLoop;

    public OnDemandEventLoop(Supplier<EventLoop> eventLoopSupplier) {
        this.eventLoopSupplier = eventLoopSupplier;
    }

    EventLoop eventLoop() {
        EventLoop el = this.eventLoop;
        if (el != null)
            return el;
        synchronized (this) {
            el = this.eventLoop;
            if (el != null)
                return el;
            return eventLoop = eventLoopSupplier.get();
        }
    }

    public boolean hasEventLoop() {
        return eventLoop != null;
    }

    @Override
    public String name() {
        return eventLoop().name();
    }

    @Override
    public void addHandler(EventHandler handler) {
        throwExceptionIfClosed();
        eventLoop().addHandler(handler);
    }

    @Override
    public void start() {
        throwExceptionIfClosed();
        eventLoop().start();
    }

    @Override
    public void unpause() {
        throwExceptionIfClosed();
        if (hasEventLoop())
            eventLoop().unpause();
    }

    @Override
    public void stop() {
        throwExceptionIfClosed();
        if (hasEventLoop())
            eventLoop().stop();
    }

    @Override
    public boolean isClosed() {
        return !hasEventLoop() || eventLoop().isClosed();
    }

    @Override
    public boolean isAlive() {
        return hasEventLoop() && eventLoop().isAlive();
    }

    @Override
    public void awaitTermination() {
        if (hasEventLoop())
            eventLoop().awaitTermination();
    }

    @Override
    public void close() {
        if (hasEventLoop())
            eventLoop().close();
    }
}

@@ -892,42 +892,8 @@
 ) %7B%0A
-        throwExceptionIfClosed();%0A
     
@@ -929,16 +929,16 @@
 ndler);%0A
+
     %7D%0A%0A 
@@ -980,42 +980,8 @@
 ) %7B%0A
-        throwExceptionIfClosed();%0A
     
@@ -1058,42 +1058,8 @@
 ) %7B%0A
-        throwExceptionIfClosed();%0A
     
@@ -1130,32 +1130,32 @@
 %0A%0A    @Override%0A
+
     public void 
@@ -1167,42 +1167,8 @@
 ) %7B%0A
-        throwExceptionIfClosed();%0A
     

Add `throwExceptionIfClosed();` to most public methods for classes implementing Closeable, https://github.com/OpenHFT/Chronicle-Core/issues/116