/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.cassandra.concurrent;

import java.lang.management.ManagementFactory;
import java.util.concurrent.*;
import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.apache.log4j.Logger;

/**
 * This is a wrapper class for the <i>ScheduledThreadPoolExecutor</i>. It provides an implementation
 * for the <i>afterExecute()</i> found in the <i>ThreadPoolExecutor</i> class to log any unexpected 
 * Runtime Exceptions.
 */

public class DebuggableThreadPoolExecutor extends ThreadPoolExecutor implements DebuggableThreadPoolExecutorMBean
{
    private static Logger logger_ = Logger.getLogger(DebuggableThreadPoolExecutor.class);

    private ObjectName objName;
    public DebuggableThreadPoolExecutor(String threadPoolName) 
    {
        this(1, 1, Integer.MAX_VALUE, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(threadPoolName));
    }

    public DebuggableThreadPoolExecutor(int corePoolSize,
            int maximumPoolSize,
            long keepAliveTime,
            TimeUnit unit,
            BlockingQueue<Runnable> workQueue,
            NamedThreadFactory threadFactory)
    {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
        super.prestartAllCoreThreads();

        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        try
        {
            objName = new ObjectName("org.apache.cassandra.concurrent:type=" + threadFactory.id);
            mbs.registerMBean(this, objName);
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }

    public long getPendingTasks()
    {
        return getTaskCount() - getCompletedTaskCount();
    }

    public void afterExecute(Runnable r, Throwable t)
    {
        super.afterExecute(r,t);

        // exceptions wrapped by FutureTask
        if (r instanceof FutureTask)
        {
            try
            {
                ((FutureTask) r).get();
            }
            catch (InterruptedException e)
            {
                throw new AssertionError(e);
            }
            catch (ExecutionException e)
            {
                logger_.error("Error in executor futuretask", e);
            }
        }

        // exceptions for non-FutureTask runnables [i.e., added via execute() instead of submit()]
        if (t != null)
        {
            logger_.error("Error in ThreadPoolExecutor", t);
        }
    }

}

@@ -1473,40 +1473,8 @@
 );%0A%0A
-    private ObjectName objName;%0A
     
@@ -1754,88 +1754,200 @@
     
-int maximumPoolSize,%0A            long keepAliveTime,%0A            TimeUnit unit,%0A
+                            int maximumPoolSize,%0A                                        long keepAliveTime,%0A                                        TimeUnit unit,%0A                            
     
@@ -1989,16 +1989,44 @@
 kQueue,%0A
+                            
         
@@ -2311,17 +2311,31 @@
     
-objName =
+mbs.registerMBean(this,
  new
@@ -2405,24 +2405,25 @@
 tory.id)
+)
 ;%0A      
       mb
@@ -2418,96 +2418,1106 @@
     
+  %7D%0A
       
-mbs.registerMBean(this, objName);%0A        %7D%0A        catch (Exception e)%0A        %7B%0A
+  catch (Exception e)%0A        %7B%0A            throw new RuntimeException(e);%0A        %7D%0A%0A        if (maximumPoolSize %3E 1)%0A        %7B%0A            this.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());%0A        %7D%0A        else%0A        %7B%0A            // preserve task serialization.  this is more complicated than it needs to be,%0A            // since TPE rejects if queue.offer reports a full queue.%0A            // the easiest option (since most of TPE.execute deals with private members)%0A            // appears to be to wrap the given queue class with one whose offer%0A            // simply delegates to put().  this would be ugly, since it violates both%0A            // the spirit and letter of queue.offer, but effective.%0A            // so far, though, all our serialized executors use unbounded queues,%0A            // so actually implementing this has not been necessary.%0A            this.setRejectedExecutionHandler(new RejectedExecutionHandler()%0A            %7B%0A                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor)%0A                %7B%0A       
     
@@ -3516,32 +3516,33 @@
                 
+ 
 throw new Runtim
@@ -3535,34 +3535,118 @@
 row new 
-RuntimeException(e
+AssertionError(%22Blocking serialized executor is not yet implemented%22);%0A                %7D%0A            %7D
 );%0A     

use CallerRunsPolicy instead of rejecting runnables on multi-threaded executors w/ blocking queues patch by jbellis; tested by Chris Were for CASSANDRA-471