Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Threads and Synchronization and the fly likes How to kill/stop a Thread Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "How to kill/stop a Thread" Watch "How to kill/stop a Thread" New topic
Author

How to kill/stop a Thread

rajshkhr pandey
Ranch Hand

Joined: Oct 14, 2009
Posts: 35
Hello to all,

In my application, using RMI and sockets, when an user logs in it creates an thread corresponding to the username. Now when user logs out I need to kill/stop the thread corresponding to that user.

How can I identify the thread corresponding to the user and how can I stop that thread?

Thanks in Advance.
Rok Štelcer
Ranch Hand

Joined: Nov 03, 2009
Posts: 101
Hi,

rajshkhr pandey wrote: How can I identify the thread corresponding to the user ...

Well, you could define e.g. a HashMap (username, created thread).
I guess this would be the easiest way ...

rajshkhr pandey wrote:... and how can I stop that thread?

You will have to declare some variable (usually a boolean), which is then checked in a loop (within a run method).
Beside this, you may also want to call an interrupt() ... just in case the thread is currently waiting or is blocked.

Hope this helps.


Regards,
Rok


SCJP, SCWCD
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12769
    
    5
Just to amplify what Rok said - you have to design your run method so that it can be exited gracefully. There are many pitfalls if you try to just arbitrarily stop a Thread. Read the java.lang.Thread documentation carefully, especially the deprecated stop() method documentation.

If the user is formally logging out rather then just disconnecting, you already have the Thread corresponding to the user so clean up of resources and a graceful exit from run should be easy with a proper architecture.

Bill
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to kill/stop a Thread