0

I am working on a simple message queue where I am creating separate thread for new connection. I want to know which variables are accessible and can be modified by multiple threads.

class RequestHandler implements Runnable {

    Socket socket;

    protected RequestHandler(Socket socket) {
        this.socket = socket;
    }

    public void run() { ..........

In above code is socket can be accessed by multiple threads, if yes then how do I protect it.

Complete code is available at. https://github.com/nakshay/JQueue

I am new to multithreading, please modify question if requried.

Akshay Naik
  • 669
  • 1
  • 6
  • 22
  • Any non-local variable can be accessed by multiple threads, provided those threads have a reference to the instance of which it is a member (or can access the member statically). – Andy Turner Oct 05 '18 at 07:40
  • That seems like a bad idea. Why not have a separate thread for each socket? https://stackoverflow.com/a/6672647/14955 – Thilo Oct 05 '18 at 07:40
  • 1
    @AndyTurner's comment is technically correct in that any number of threads can access any fields they have a reference to, but in order to make sure that updates to those fields become visible properly, you have to think about thread synchronization (`final` immutable or `synchronized` or `volatile` or such). – Thilo Oct 05 '18 at 07:45

2 Answers2

2

If the socket variable can be accessed by multiple threads you need synchronize access to the variable.

One of the ways is to create a wrapper, which basically will synchronize methods calls[1].

And then wrap your socket in the constructor:

class RequestHandler implements Runnable {

    Socket socket;

    protected RequestHandler(Socket socket) {
        this.socket = new SynchronizedSocket(socket);
    }

    public void run() { ..........

[1] - https://gist.github.com/Sammers21/a6635213276e9ea064a5a4f20dd53c11

Sammers
  • 1,038
  • 2
  • 8
  • 20
1

Not shown in the post: You actually create a new RequestHandler and Socket for every thread, so since the socket is not static, you are fine. Each thread handles its own connection (represented by the Socket).

kutschkem
  • 7,826
  • 3
  • 21
  • 56