Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6368047
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T00:37:34+00:00 2026-05-25T00:37:34+00:00

I am a Java newbie trying to learn network programming and concurrency, and I

  • 0

I am a Java newbie trying to learn network programming and concurrency, and I thought I’d try out writing a simple chat server where input from a client is echoed to all the clients. That’s not happening. I added a couple print statements so that the program will announce that it is waiting for connections and each time it receives a connection. I am using Telnet locally to connect to the port on my machine.

The program announces success for the first and second concurrent connections but then does not announce success for subsequent connections until I close all connections. So, for example, I’ll connect from five separate terminals, and the program will announce “Connection 1” and “Connection 2” but will not announce “Connection 3”, 4, and 5 until I close all the terminals.

I’m looking for help figuring out where my errors lie as well as general advice for how to approach debugging a situation like this.

In a nutshell, my program has

  1. A Main class, which starts the other three threads
  2. A ClientListener class, which uses a SocketReader to listen for connections and stores the Sockets inputstreams and outputstreams in two Sets.
  3. A MessageReader, which iterates over the inputstreams. If it finds a message, it puts it in a SynchronousQueue and waits for the
  4. MessageWriter to remove it. The MessageWriter sends the message to all the outputstreams.

The code is below. Thanks for any help!

public class Main {

    public static void main(String[] args) {
        ClientListener clientListener = new ClientListener();
        Thread clientListenerThread = new Thread(clientListener);
        clientListenerThread.setPriority(Thread.MAX_PRIORITY);
        clientListenerThread.start();

        MessageReader messageReader = new MessageReader(clientListener);
        Thread messageReaderThread = new Thread(messageReader);
        messageReaderThread.setPriority(Thread.MIN_PRIORITY);
        messageReaderThread.start();

        MessageWriter messageWriter = new MessageWriter(messageReader, clientListener);
        Thread messageWriterThread = new Thread(messageWriter);
        messageWriterThread.setPriority(Thread.NORM_PRIORITY);
        messageWriterThread.start();
    }
}

public class ClientListener implements Runnable {
    private static final int DEFAULT_PORT = 5000;

    private Set<Scanner> clientIn = Collections.synchronizedSet(
            new LinkedHashSet<Scanner>());
    private Set<PrintWriter> clientOut = Collections.synchronizedSet(
            new LinkedHashSet<PrintWriter>());

    public Set<Scanner> getClientIn() {
        return clientIn;
    }

    public Set<PrintWriter> getClientOut() {
        return clientOut;
    }

    @Override
    public void run() {
        try {
            ServerSocket server = new ServerSocket(DEFAULT_PORT);
            System.out.println("Listening for connections...");
            int connectionNum = 0;

            while(true) {
                Socket socket = server.accept();
                connectionNum++;
                System.out.format("Connection %s%n", connectionNum);

                Scanner in = new Scanner(socket.getInputStream());
                PrintWriter out = new PrintWriter(socket.getOutputStream());
                clientIn.add(in);
                clientOut.add(out);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


public class MessageReader implements Runnable {
    private ClientListener clientListener;
    private BlockingQueue<String> messages = new SynchronousQueue<String>();

    public MessageReader(ClientListener clientListener) {
        this.clientListener = clientListener;
    }

    @Override
    public void run() {
        while(true) {
            Set<Scanner> clients = clientListener.getClientIn();
            synchronized (clients) {
                for(Scanner client: clients) {
                    if(client.hasNext()) {
                        try {
                            messages.put(client.next());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public String getMessage() throws InterruptedException {
        return messages.take();
    }
}


public class MessageWriter implements Runnable {
    private ClientListener clientListener;
    private MessageReader messageReader;

    public MessageWriter(
            MessageReader messageReader, 
            ClientListener clientListener) {
        this.messageReader = messageReader;
        this.clientListener = clientListener;
    }

    @Override
    public void run() {
        try {

            while(true) {
                String message = messageReader.getMessage();

                Set<PrintWriter> clients = clientListener.getClientOut();
                synchronized (clients) {
                    for(PrintWriter client: clients) {
                        client.println(message);
                    }
                }
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T00:37:35+00:00Added an answer on May 25, 2026 at 12:37 am

    I’m not a threading expert, but in class MessageReader there is this line

    if(client.hasNext())
    

    Javadoc for Scanner.hasNext() say’s “This method may block while waiting for input to scan. The scanner does not advance past any input.”

    If the scanner is still in wait the synchronized method never proceeds and block all other inputs. And as said in my earlier comment the line which says clientIn.add(in); in class ClientListener probably gets blocked given that its a synchronized Set, but since the print statment is written before it, it might give the impression that Connection 2 was succesfully established.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm a Java newbie. I'm trying to figure out whether a number is a
I am a newbie in Java. I am trying to figure out how to
I am a newbie to AS400-Java programming. I am trying to create my first
Newbie to C++ but I am a Java programmer. Trying to learn C++ now.
I realise this is a newbie question, but as I'm trying to learn C++
Java newbie. I am trying to run a java main class from cmd line
I am a newbie trying to figure out the pros and cons of using
Hey, guys. Newbie to tomcat/apache, java returner here. I'm trying to run th step-by-step
I am newbie to java programming language. My problem is: I want to read
I am a newbie Scala developer trying to figure out how to design a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.