Stop a Thread by updating a variable in run(). Having problem in the line "socket.accept" (inside the run), because it is a blocking call.
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Sakibul_Khan
Posted On:   Sunday, April 6, 2003 03:33 PM

Hi, Please look at the following code:- import java.net.*; import java.io.*; public class EmailServer extends Thread{ private Thread emailServerThread; public EmailServer(){} public void run(){ int i = 1; System.out.println("Inside RUN"); try { ServerSocket s = new ServerSocket(62389);/* poor code: static port # */ emailServerThread = Thread.currentThread(); while( emailServerThread == Thread.currentThread() ){ System.out.println("Inside while"); Socket incoming = s.accept( );//////THIS LINE IS CAUSING THE PROBLEM, even though "stop2()" updates "emailServe   More>>

Hi,



Please look at the following code:-



			
import java.net.*;
import java.io.*;

public class EmailServer extends Thread{
private Thread emailServerThread;
public EmailServer(){}

public void run(){
int i = 1;
System.out.println("Inside RUN");
try {
ServerSocket s = new ServerSocket(62389);/* poor code: static port # */
emailServerThread = Thread.currentThread();

while( emailServerThread == Thread.currentThread() ){
System.out.println("Inside while");
Socket incoming = s.accept( );//////THIS LINE IS CAUSING THE PROBLEM, even though "stop2()" updates "emailServerThread" to null, but the blocking call "s.accept" is not returning, hence the run method never exits.

System.out.println("Spawning " + i);
//new ThreadedEchoHandler(incoming, i).start();
new EmailServerHandler(incoming, i).start();
/* Note the use of "i" as a tool to observe the concurrency between multiple clients. */
i++;
}//while
} catch (Exception e){
System.out.println(e);
}
System.out.println("EmailServer: Got out of RUN() method !!!");
}
public void stop2(){
System.out.println("Inside STOP2");
emailServerThread = null;
}
}
// ****************************************************
class EmailServerHandler extends Thread {

private Socket incoming;
private int counter;

public EmailServerHandler(Socket i, int c) {
incoming = i; counter = c;
}

public void run() {
// Something ....
}
}



Thanx in advance.

------------------------------------SAKIB
   <<Less

I found the solution by myself.

Posted By:   Sakibul_Khan  
Posted On:   Sunday, April 6, 2003 07:14 PM

Hi,



I am posting my own solution for those who also have similar problems. Just close the socket connection & you get out of the while(true) because an exception is generated when a socket is blocked at "s.accept()" & you suddenly do "s.close()".



Hence, in the above code, I just made the "ServerSocket s" variable global insetad of local & added this extra line to "stop2()":-

s.close();

This will generate an exception in the "while()" of the run() method & caught by the "catch" after the "while".



---------------------------------SAKIB
About | Sitemap | Contact