/*
 * Copyright 2016-2018 shardingsphere.io.
 * <p>
 * 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.
 * </p>
 */

package io.shardingsphere.proxy.frontend.mysql;

import io.netty.channel.ChannelId;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Manage the thread for each channel invoking.
 * 
 * <p>This ensure atomikos can process XA transaction by current thread id.</p>
 * 
 * @author zhaojun
 */
public class ChannelThreadHolder {
    
    private static Map<ChannelId, ExecutorService> threadPoolMap = new ConcurrentHashMap<>();
    
    /**
     * Get active single thread pool of current channel.
     *
     * @param channelId channel id
     * @return thread pool
     */
    public static ExecutorService get(final ChannelId channelId) {
        ExecutorService newExecutorService = Executors.newSingleThreadExecutor();
        ExecutorService existedExecutorService = threadPoolMap.putIfAbsent(channelId, newExecutorService);
        if (null != existedExecutorService) {
            newExecutorService.shutdown();
            return existedExecutorService;
        }
        return newExecutorService;
    }
    
    /**
     * Remove thread when channel was closed.
     *
     * @param channelId channel id
     */
    public static void remove(final ChannelId channelId) {
        threadPoolMap.remove(channelId).shutdown();
    }
}

@@ -1573,9 +1573,9 @@
 ull 
-!
+=
 = ex
@@ -1610,16 +1610,23 @@
         
+return 
 newExecu
@@ -1635,27 +1635,16 @@
 rService
-.shutdown()
 ;%0A      
@@ -1648,27 +1648,22 @@
     
+ %7D%0A
      
-return existed
+   new
 Exec
@@ -1677,38 +1677,43 @@
 vice
-;%0A        %7D%0A        return new
+.shutdown();%0A        return existed
 Exec

make ChannelThreadHolder.get() thread safe