My main class defines the ExecutorService object with newFixedThreadPool of 3 threads.
public static void main(String[] args) {
queue = new ArrayBlockingQueue<HashMap<String, String>>(MAX_QUEUE_LENGTH);
socketThreads = Executors.newFixedThreadPool(3);
socketThreads.submit(new MyListener(PORT1, queue));
socketThreads.submit(new MyListener(PORT2, queue));
socketThreads.submit(new MyListener(PORT3, queue));
}
The Runnables are submitted. Runnables are as follows:
public class MyListener implements Runnable {
private static ServerSocket listener = null;
// private Socket socket = null;
private InputStream inStream = null;
private OutputStream outStream = null;
private static ArrayBlockingQueue < HashMap < String, String >> queue = null;
private static Logger LOGGER = LogManager.getLogger(MyListener.class);
int port;
public MyListener(int port, ArrayBlockingQueue < HashMap < String, String >> queue) {
try {
listener = new ServerSocket(port);
this.queue = queue;
this.port = port;
} catch (IOException e) {
LOGGER.fatal("Could not connect to the socket, port number: " + port, e);
}
}
@
Override
public void run() {
do {
try {
LOGGER.debug("*** 1 ***");
Socket socket = listener.accept();
LOGGER.debug("*** 2 ***");
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
HashMap < String, String > map = (HashMap < String, String > ) ois.readObject();
LOGGER.debug("*** 3 ***");
queue.add(map);
} catch (IOException e) {
LOGGER.fatal("Error in socket connection ", e);
} catch (ClassNotFoundException e) {
LOGGER.fatal("Error - Class not found ", e);
} catch (ClassCastException e) {
LOGGER.fatal("Error - Class Cast Exception ", e);
}
} while (true);
}
}
So, basically the socket reads an incoming data and adds that to the queue. The idea is that once the request comes in and is obtained, the socket should again start waiting for the connection. My code works when I have a single thread pool running but doesn't work if I start > 1 threads in the pool. As you can see in the code, the execution reaches log statement * * * 1 * * * and the accept never happens.
I tried to separate out the ObjectnputStream from this and run it a separate runnable, but that does not help either after reading Creating a socket server which allows multiple connections via threads and Java. Any reason why this happens?