Hey,
I'm working on a multiuser server. For every client I create a thread. I however face issues with my InputStreamReader blocking the thread whenever multiple requests are made at the same time (in fact if the InputStream reader is blocking, every request is scheduled instead and executed once finished).
I have a minimal example which demonstrated the problem:
ServerTest.java:
package servertest; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class ServerTest { public static void main(String[] args) throws IOException { ServerSocket server = new ServerSocket(1234); Socket s; while (true) { s = server.accept(); ServerThread t = new ServerThread(s); t.start(); }}}
ServerThread.java:
package servertest; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.logging.Level; import java.util.logging.Logger; public class ServerThread extends Thread { private Socket s; public ServerThread(Socket s) { this.s = s; } @Override public void run() { try { BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream())); String text = in.readLine(); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); System.out.println("Sleeping..."); Thread.sleep(8000); out.write(text.toUpperCase()); out.newLine(); out.flush(); out.close(); in.close(); } catch (IOException | InterruptedException ex) { System.out.println("Error: " + ex); } } }
Now whenever you request localhost:1234 twice, you will face one thread executing (Thread.sleep(8000)) while the second "waits" until the InputStreamReader is finished.
I think this is a design problem. Will I need an additional thread just for the InputStreamReader? If so, where?:/
This error has caused alot of headache to me already (first to find out that this was the actual cause, second the attempt to find a solution for this), so any help is highly appreaciated!