• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 204
  • Last Modified:

Threading a method

Ola,

I have build this ChatServer Object Model in java.
One of its methods is Start()
The Start method executes a blocking while ( true ) loop listening for connections
Now how do I enable for the ChatServers Stop() method to be called while the Start method is still blocking?

public class GenericChatServer
{
    public GenericChatServer() { }
    public void Start()
    {
        while ( true )
        {
            // listen for connections ( that is blocking )
        }
    }
    public void Stop()
    {
        // STop listening for connections but this will never run since Start is blocking :-(
    }
}
0
DaFou
Asked:
DaFou
  • 6
  • 5
  • 4
  • +3
3 Solutions
 
RMaruszewskiCommented:
Set the boolean variable indicating that the thread is to be stopped:

public class GenericChatServer
{
    public boolean stopMeNow = false;

    public GenericChatServer() { }
    public void Start()
    {
        while ( true )
        {
            // listen for connections ( that is blocking )

          if (stopMeNow)
            break;
        }
    }
    public void Stop()
    {
      stopMeNow = true;
        // STop listening for connections but this will never run since Start is blocking :-(
    }
}
0
 
DaFouAuthor Commented:
that will not work. what if a new connection never comes. Then the programm will wait forever for that new connection to come after wich it can stop running.
No.... I'll be needing threads

any advice?
0
 
objectsCommented:
close the socket, that should cause the blocking call to throw an exception.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
DaFouAuthor Commented:
but how can i close the socket when the first time anything from the call stack will be excucted is after the next incomming connection came ( which could be never ) .
0
 
RMaruszewskiCommented:
Ok. Paste the code for this fragment, please:
// listen for connections ( that is blocking )

(as there must be a method to interrupt this process...)

> but how can i close the socket when the first time anything from the call stack will be excucted is after the next incomming connection came ( which could be never )

Erm... Sorry, I'm unable to understand this sentence. :-/
0
 
tusharganguliCommented:
here is the code which i think would make your program to be run in a threaded environment:

in the following code snippet, Start and Stop are running simultaneousy in a multi threaded environment:


public class GenericChatServer implements Runnable
{
    public GenericChatServer() { }
    public void Start()
    {
        Thread th = new Thread(this);
            th.start();
            
    }
    public void Stop()
    {
        while(true)
            System.out.println("stop thread");
            // STop listening for connections but this will never run since Start is blocking :-(
    }

      public void run() {
                  
                  while ( true )
                  {
                        System.out.println("start thread");
                        // listen for connections ( that is blocking )
                  }
      }

      public static void main(String[] args) {
            GenericChatServer obj = new GenericChatServer();
            obj.Start();
            obj.Stop();
      }
}


if this is not what you want then please do specify :
From where should the Stop function be called
1: from inside the start function
2. or from some other class
0
 
DaFouAuthor Commented:
tusharganguli, I think this is exactly what I want.
The Stop method will be called from outside the ChatServer Itself.

but i fail to see how the thread that started the start method is stopped in the Stop method. other then that i think this aproach will work
0
 
RMaruszewskiCommented:
Well, if everything else fails (that is: you won't be able to interrupt blocking process on regular basis), you can always use method Thread.interrupt().
0
 
DaFouAuthor Commented:
well yes but the Thread is created inside the start method and therefore its scope inside that method only. Now how do I access that thread from inside the Stop method
0
 
CEHJCommented:
You need a combination of the suggestions of objects and tusharganguli as you probably won't be able to stop or intterupt blocking socket IO without closing it
0
 
RMaruszewskiCommented:
Excerpt from Java API (Thread.interrupt):
"If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException."

So... it may work, I guess.
0
 
CEHJCommented:
But the above is not using an interruptible channel - it's using standard IO.
0
 
DaFouAuthor Commented:
I think I understand now.. IS this a combo of objects's suggestion and tusharganguli's suggestion?

public class GenericChatServer implements Runnable
{
    private ServerSocket prServerSocket;
    public GenericChatServer() { }
    public void Start()
    {
        Thread th = new Thread(this);
          th.start();
         
    }
    public void Stop()
    {
        prServerSocket.Close() // or what ever method closes this Socket
    }

     public void run() {
               
               prServerSocket = new ServerSocket( 111 );
               System.out.println("start thread");
               while ( true )
               {
                    Socket lSocket = prServerSocket.Accept();
               }
     }

     public static void main(String[] args) {
          GenericChatServer obj = new GenericChatServer();
          obj.Start();
          obj.Stop();
     }
}
0
 
CEHJCommented:
That's getting there, but are you intending this to be able to accept multiple simultaneous connections, or just the one?
0
 
DaFouAuthor Commented:
Multiple.. but I posted pseudo code. I am going to do something like this in the run method:
public void run() {
               
               prServerSocket = new ServerSocket( 111 );
               System.out.println("start thread");
               while ( true )
               {
                    Socket lSocket = prServerSocket.Accept();
                    // Store the Socket in a Client object and store the Client object in a ClientsCollection object
               }
     }
0
 
CEHJCommented:
To use more pseudo-ish code, you need something more like:


while (contineAcceptingConnections) {
      Socket socket = prServerSocket.accept();
      new RunnableObjectEncapsulatingASocketAndAThread(socket).start();
}



0
 
esorfCommented:
You'll need to wait between these two lines
          obj.Start();
          obj.Stop();

because Start() doesn't block, it just starts your listening thread.
0
 
objectsCommented:
> but how can i close the socket when the first time anything from the call stack will be excucted is after the next incomming connection came ( which could be never ) .

You have to stop the thread from another thread (reagrdless of what means you use).
Sorry I should have been clearer.
0
 
CEHJCommented:
:-)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 6
  • 5
  • 4
  • +3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now