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 :-(
    }
}
LVL 2
DaFouAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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
Cloud Class® Course: Microsoft Exchange Server

The MCTS: Microsoft Exchange Server 2010 certification validates your skills in supporting the maintenance and administration of the Exchange servers in an enterprise environment. Learn everything you need to know with this course.

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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.