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 3941614
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T00:33:50+00:00 2026-05-20T00:33:50+00:00

Ok, here is my problem. I need to create a socket program that can

  • 0

Ok, here is my problem.

I need to create a socket program that can handle multiple connection from my client apps (lets call it apps1). I handle this using thread (so each connection was thrown into a new thread)

The problem is I can accept request from all open connection but when I want to send a response , I must send it through the latest connection only. So if I have 3 connections (con1,con2,con3) I can accept request from con1, con2 and con3 but I must send the response through con3 (assuming con3 is the latest connection)

I thought of using a singleton, with a PrintWriter parameter. So everytime there is a new connection ,they call the singleton and update the parameter and when I want to send the response, I get the PrintWriter first before sending.

Here is my Singleton class :

public class Singleton {

private static final Singleton instance = new Singleton();

PrintWriter  out;

public static Singleton getInstance() {
    return instance;
}
public Singleton ()
{
    if (instance != null) {
        throw new IllegalStateException("Already instantiated");
    }
}

public PrintWriter getPrintWriter ()
{
    return this.out;
}
public void updatePrintWriter (PrintWriter  out){
    this.out = out;
}
}

This is my main program :

public class SocketAccept{
private ServerSocket mainSocket;
private Socket clientSocket;

    public SocketAccept (int portNumber) {
        Singleton s = Singleton.getInstance();
        do {
        try {
            mainSocket = new ServerSocket(portNumber);
            clientSocket = mainSocket.accept();
            s.updatePrintWriter(new PrintWriter(clientSocket.getOutputStream(), true));
            ClientThread (clientSocket);
        } catch (IOException ex) {
            Logger.getLogger(TestClass.class.getName()).log(Level.SEVERE, null, ex);
        }
        }while (true);//need to change this into thread pool or connection pool    
    } 
}

and this is my thread that handle socket :

public class ClientThread extends Thread {

    private Socket cs;
    Singleton s = Singleton.getInstance();
    PrintWriter out;

    private String read(Socket sc) {
        String request = "";
        //read request here
        return request;
    }

    private String process(String request) {
        String response = "";
        //process request here
        return response;
    }

    public ClientThread(Socket clientSocket) {
        this.cs = clientSocket;
    }

    @Override
    public void run() {
        String requestMsg = "";
        String responseMsg = "";
        do {
            requestMsg = read(cs);// read the message

            if (requestMsg.equalsIgnoreCase("SHUTDOWN")) {
                break;
            }
            responseMsg = process(requestMsg);
            out = s.getPrintWriter();
            out.write(responseMsg);
        } while (true);
    }
}

Do I did it right? Or it is impossible to do it with singleton?

Thanks for the help.

  • 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-20T00:33:51+00:00Added an answer on May 20, 2026 at 12:33 am

    Unfortunately, that is not a thread safe implementation of the Singleton pattern. I don’t think you need one in this case either, an AtomicReference will probably work just fine. Try this:

    public class SocketAccept{
        private ServerSocket mainSocket;
        private Socket clientSocket;
    
        private final AtomicReference<PrintWriter> printWriterHolder = new AtomicReference(null);
    
        public SocketAccept (int portNumber) {
            Singleton s = Singleton.getInstance();
            do {
            try {
                mainSocket = new ServerSocket(portNumber);
                clientSocket = mainSocket.accept();
                printWriterHolder.set(new PrintWriter(clientSocket.getOutputStream(), true));
                Thread clientThread = new ClientThread (clientSocket, printWriterHolder);
                clientThread.start();
            } catch (IOException ex) {
                Logger.getLogger(TestClass.class.getName()).log(Level.SEVERE, null, ex);
            }
            }while (true);//need to change this into thread pool or connection pool    
        } 
    }
    

    …

    public class ClientThread extends Thread
        ...
        private final AtomicReference<PrintWriter> printWriterHolder;
        public ClientThread(Socket clientSocket, AtomicReference<PrintWriter> holder) {
            this.cs = clientSocket;
            this.printWriterHolder = holder;
        }
    
        @Override
        public void run() {
            String requestMsg = "";
            String responseMsg = "";
            do {
                requestMsg = read(cs);// read the message
    
                if (requestMsg.equalsIgnoreCase("SHUTDOWN")) {
                    break;
                }
                responseMsg = process(requestMsg);
                out = printWriterHolder.get();
                out.write(responseMsg);
            } while (true);
        }
    }
    

    If you really do want to use the Singleton pattern, here is a reference from SO where the question has a good thread-safe implementation for creating the Singleton: Java Singleton Pattern

    You will also need to make accessing the Singleton’s state thread-safe by using synchronized, Lock, or atomic operations (AtomicInteger, AtomicReference, etc..) as necessary.

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

Sidebar

Related Questions

I've got a problem here with an MSI deployment that I'm working on (using
I'm having a strange problem here... I have an ASP.NET 3.5 application that has
I've got a Schroedinger's Cat type of problem here -- my program (actually the
Here's the problem, you include multiple assemblies and add 'using namespaceX' at the top
Just a small SVN problem here. I setup my own SVN server Setting up
I'm having a bit of a problem here. We have 2 urls let me
This is in reference to the question previously asked The problem here is, each
Here's a problem I ran into recently. I have attributes strings of the form
Here is a problem I've struggled with ever since I first started learning object-oriented
Here's my problem - I'd like to communicate between two websites and I'm looking

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.