/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project 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 io.netty.channel.socket.aio;

import io.netty.channel.EventExecutor;
import io.netty.channel.EventLoopException;
import io.netty.channel.MultithreadEventLoop;

import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.channels.AsynchronousChannelGroup;
import java.util.concurrent.ThreadFactory;

public class AioEventLoop extends MultithreadEventLoop {

    final AsynchronousChannelGroup group;

    public AioEventLoop() {
        this(0);
    }

    public AioEventLoop(int nThreads) {
        this(nThreads, null);
    }

    public AioEventLoop(int nThreads, ThreadFactory threadFactory) {
        super(nThreads, threadFactory);
        try {
            group = AsynchronousChannelGroup.withThreadPool(this);
        } catch (IOException e) {
            throw new EventLoopException("Failed to create an AsynchronousChannelGroup", e);
        }
    }

    @Override
    public void execute(Runnable command) {
        Class<? extends Runnable> commandType = command.getClass();
        if (commandType.getName().startsWith("sun.nio.ch.")) {
            executeAioTask(command);
        } else {
            super.execute(command);
        }
    }

    private void executeAioTask(Runnable command) {
        AbstractAioChannel ch = null;
        try {
            ch = findChannel(command);
        } catch (Throwable t) {
            // Ignore
        }

        EventExecutor l;
        if (ch != null) {
            l = ch.eventLoop();
        } else {
            l = unsafe().nextChild();
        }

        if (l.isShutdown()) {
            command.run();
        } else {
            l.execute(command);
        }
    }

    private static AbstractAioChannel findChannel(Runnable command) throws Exception {
        // TODO: Optimize me
        Class<?> commandType = command.getClass();
        for (Field f: commandType.getDeclaredFields()) {
            if (f.getType() == Runnable.class) {
                f.setAccessible(true);
                AbstractAioChannel ch = findChannel((Runnable) f.get(command));
                if (ch != null) {
                    return ch;
                }
            }

            if (f.getType() == Object.class) {
                f.setAccessible(true);
                Object candidate = f.get(command);
                if (candidate instanceof AbstractAioChannel) {
                    return (AbstractAioChannel) candidate;
                }
            }
        }

        return null;
    }

    @Override
    protected EventExecutor newChild(ThreadFactory threadFactory, Object... args) throws Exception {
        return new AioChildEventLoop(this, threadFactory);
    }
}

@@ -928,91 +928,407 @@
 til.
-concurrent.ThreadFactory;%0A%0Apublic class AioEventLoop extends MultithreadEventLoop %7B
+ArrayDeque;%0Aimport java.util.Deque;%0Aimport java.util.concurrent.ConcurrentHashMap;%0Aimport java.util.concurrent.ConcurrentMap;%0Aimport java.util.concurrent.ThreadFactory;%0A%0Apublic class AioEventLoop extends MultithreadEventLoop %7B%0A%0A    private static final ConcurrentMap%3CClass%3C?%3E, Field%5B%5D%3E fieldCache = new ConcurrentHashMap%3CClass%3C?%3E, Field%5B%5D%3E();%0A    private static final Field%5B%5D FAILURE = new Field%5B0%5D;
 %0A%0A  
@@ -2706,28 +2706,916 @@
     
-// TODO: Optimize me
+Class%3C?%3E commandType = command.getClass();%0A        Field%5B%5D fields = fieldCache.get(commandType);%0A        if (fields == null) %7B%0A            try %7B%0A                fields = findFieldSequence(command, new ArrayDeque%3CField%3E(2));%0A            %7D catch (Throwable t) %7B%0A                // Failed to get the field list%0A            %7D%0A%0A            if (fields == null) %7B%0A                fields = FAILURE;%0A            %7D%0A%0A            fieldCache.put(commandType, fields); // No need to use putIfAbsent()%0A        %7D%0A%0A        if (fields == FAILURE) %7B%0A            return null;%0A        %7D%0A%0A        final int lastIndex = fields.length - 1;%0A        for (int i = 0; i %3C lastIndex; i ++) %7B%0A            command = (Runnable) fields%5Bi%5D.get(command);%0A        %7D%0A%0A        return (AbstractAioChannel) fields%5BlastIndex%5D.get(command);%0A    %7D%0A%0A    private static Field%5B%5D findFieldSequence(Runnable command, Deque%3CField%3E fields) throws Exception %7B
 %0A   
@@ -3827,43 +3827,100 @@
     
-AbstractAioChannel ch = findChannel
+fields.addLast(f);%0A                try %7B%0A                    Field%5B%5D ret = findFieldSequence
 ((Ru
@@ -3941,19 +3941,31 @@
 command)
-);%0A
+, fields);%0A    
         
@@ -3968,34 +3968,35 @@
             if (
-ch
+ret
  != null) %7B%0A    
@@ -4015,17 +4015,113 @@
     
+    
 return 
-ch
+ret;%0A                    %7D%0A                %7D finally %7B%0A                    fields.removeLast()
 ;%0A  
@@ -4229,32 +4229,93 @@
 cessible(true);%0A
+                fields.addLast(f);%0A                try %7B%0A    
                 
@@ -4341,32 +4341,36 @@
 f.get(command);%0A
+    
                 
@@ -4440,45 +4440,150 @@
     
+    
 return 
-(AbstractAioChannel) candidate
+fields.toArray(new Field%5Bfields.size()%5D);%0A                    %7D%0A                %7D finally %7B%0A                    fields.removeLast()
 ;%0A  

Optimize AioEventLoop.findChannel()