package backtype.storm.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;

public class InprocMessaging {
    private static Map<Integer, LinkedBlockingQueue<Object>> _queues = new HashMap<Integer, LinkedBlockingQueue<Object>>();
    private static final Object _lock = new Object();
    private static int port = 1;
    
    public static int acquireNewPort() {
        int ret;
        synchronized(_lock) {
            ret = port;
            port++;
        }
        return ret;
    }
    
    public static void sendMessage(int port, Object msg) {
        LinkedBlockingQueue<Object> queue = getQueue(port);
        synchronized(_lock) {
            queue.add(msg);
        }
    }
    
    public static Object takeMessage(int port) throws InterruptedException {
        LinkedBlockingQueue<Object> queue = getQueue(port);
        Object ret = queue.take();
        synchronized(_lock) {
            if(queue.size()==0) {
                _queues.remove(port);
            }
        }
        return ret;
    }

    public static Object pollMessage(int port) {
        LinkedBlockingQueue<Object> queue = getQueue(port);
        Object ret = queue.poll();
        synchronized(_lock) {
            if(queue.size()==0) {
                _queues.remove(port);
            }
        }
        return ret;
    }    
    
    private static LinkedBlockingQueue<Object> getQueue(int port) {
        synchronized(_lock) {
            if(!_queues.containsKey(port)) {
              _queues.put(port, new LinkedBlockingQueue<Object>());   
            }
            return _queues.get(port);
        }
    }

}

@@ -613,752 +613,252 @@
     
-LinkedBlockingQueue%3CObject%3E queue = getQueue(port);%0A        synchronized(_lock) %7B%0A            queue.add(msg);%0A        %7D%0A    %7D%0A    %0A    public static Object takeMessage(int port) throws InterruptedException %7B%0A        LinkedBlockingQueue%3CObject%3E queue = getQueue(port);%0A        Object ret = queue.take();%0A        synchronized(_lock) %7B%0A            if(queue.size()==0) %7B%0A                _queues.remove(port);%0A            %7D%0A        %7D%0A        return ret;%0A    %7D%0A%0A    public static Object pollMessage(int port) %7B%0A        LinkedBlockingQueue%3CObject%3E queue = getQueue(port);%0A        Object ret = queue.poll();%0A        synchronized(_lock) %7B%0A            if(queue.size()==0) %7B%0A                _queues.remove(port);%0A            %7D%0A        %7D%0A        return ret
+getQueue(port).add(msg);%0A    %7D%0A    %0A    public static Object takeMessage(int port) throws InterruptedException %7B%0A        return getQueue(port).take();%0A    %7D%0A%0A    public static Object pollMessage(int port) %7B%0A        return  getQueue(port).poll()
 ;%0A  

make InprocMessaging threadsafe to fix lost messages with FeederSpout