/*
 * Copyright 2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.dempsy.util.executor;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * This is a scheduler that will schedule a task to run in the future (or now) and when that task completes it shuts itself down. It can be thought of almost as
 * a daemon task scheduler.
 */
public final class AutoDisposeSingleThreadScheduler {
    private final String baseThreadName;
    private long pendingCalls = 0L;

    private static final AtomicLong sequence = new AtomicLong(0);
    private ScheduledExecutorService scheduler = null;

    public AutoDisposeSingleThreadScheduler(final String baseThreadName) {
        this.baseThreadName = baseThreadName;
    }

    /**
     * This object is returned from {@link AutoDisposeSingleThreadScheduler#schedule(Runnable, long, TimeUnit)} and can be used to cancel the task - best
     * effort.
     */
    public class Cancelable implements Runnable {
        private boolean cancelled = false;

        private final ScheduledFuture<?> future;
        private final Runnable proxied;

        // called only with a lock on the outer instance.
        private Cancelable(final Runnable runnable, final long timeout, final TimeUnit units) {
            this.proxied = runnable;
            this.future = getScheduledExecutor().schedule(this, timeout, units);
            pendingCalls++;
        }

        /**
         * Attempt to cancel the Runnable that was submitted to {@link AutoDisposeSingleThreadScheduler#schedule(Runnable, long, TimeUnit)}
         */
        public void cancel() {
            synchronized(AutoDisposeSingleThreadScheduler.this) {
                future.cancel(false);
                cancelled = true;
                decrement();
            }
        }

        @Override
        public void run() {
            // running the proxied can resubmit the task ... so we dispose afterward
            synchronized(AutoDisposeSingleThreadScheduler.this) {
                if(cancelled)
                    return;
            }

            try {
                proxied.run();
            } finally {
                synchronized(AutoDisposeSingleThreadScheduler.this) {
                    if(!cancelled) // if it was cancelled then it was already decremented
                        decrement();
                }
            }
        }

        /**
         * Is the Runnable that was submitted to {@link AutoDisposeSingleThreadScheduler#schedule(Runnable, long, TimeUnit)} comleted?
         */
        public boolean isDone() {
            return future.isDone();
        }

        private void decrement() {
            synchronized(AutoDisposeSingleThreadScheduler.this) {
                pendingCalls--;
                if(pendingCalls <= 0)
                    disposeOfScheduler();
            }
        }
    }

    /**
     * Schedule the given Runnable to run at the given time period from now. The scheduler resources will be cleaned up once the task runs.
     */
    public synchronized Cancelable schedule(final Runnable runnable, final long timeout, final TimeUnit units) {
        return new Cancelable(runnable, timeout, units);
    }

    private synchronized final ScheduledExecutorService getScheduledExecutor() {
        if(scheduler == null) {
            if(baseThreadName != null)
                scheduler = Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, baseThreadName + "-" + sequence.getAndIncrement()));
            else
                scheduler = Executors.newSingleThreadScheduledExecutor();

        }
        return scheduler;
    }

    private synchronized final void disposeOfScheduler() {
        if(scheduler != null)
            scheduler.shutdown();
        scheduler = null;
    }
}

@@ -1115,16 +1115,173 @@
 duler %7B%0A
+    /**%0A     * The daemon status of the scheduled thread is defaulted to this value.%0A     */%0A    public final static boolean DEFAULT_DAEMON_STATUS = false;%0A%0A
     priv
@@ -1309,24 +1309,24 @@
 ThreadName;%0A
-
     private 
@@ -1470,16 +1470,50 @@
  = null;
+%0A    private final boolean daemon;
 %0A%0A    pu
@@ -1577,24 +1577,181 @@
 readName) %7B%0A
+        this(baseThreadName, DEFAULT_DAEMON_STATUS);%0A    %7D%0A%0A    public AutoDisposeSingleThreadScheduler(final String baseThreadName, final boolean daemon) %7B%0A
         this
@@ -1780,24 +1780,54 @@
 ThreadName;%0A
+        this.daemon = daemon;%0A
     %7D%0A%0A    /
@@ -4430,33 +4430,45 @@
 readName != null
-)
+ %7C%7C daemon) %7B
 %0A               
@@ -4527,16 +4527,60 @@
 tor(r -%3E
+ %7B%0A                    final Thread thread =
  new Thr
@@ -4636,17 +4636,16 @@
 ement())
-)
 ;%0A      
@@ -4649,16 +4649,119 @@
         
+         thread.setDaemon(daemon);%0A                    return thread;%0A                %7D);%0A            %7D
  else%0A  

Allow the AutoDisposeSingleThreadScheduler to run it's thread as a daemon.