It's not a secret anymore!
The moose likes Threads and Synchronization and the fly likes Notifying a thread event. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Notifying a thread event." Watch "Notifying a thread event." New topic

Notifying a thread event.

Anirvan Majumdar
Ranch Hand

Joined: Feb 22, 2005
Posts: 261
hello everyone
my situation is something like this:
I have a parent class which has a method to retrieve data from a file. This data can be received in anything from 2 to 20 seconds. Now i am supposed to time this data retrieval and stop the retrieval if it exceeds 20 seconds.
So just before i invoke the data retrieval method i instantiate a thread which times the retrival. However, i cannot figure out when 20 sec are up how do i send back a message from the thread class to the parent class.

public class Parent {
public XYZ(){
timerThread timer=new timerThread();
getFileData(); // This is the action i have to time

class timerThread extends Thread{
public void run() {
long ElapsedTime=0;
if (ElapsedTime>20 seconds){
..<<somehow notify Parent class>>...

If someone could enumerate a possible solution with the help of a small code snippet i'd be very grateful. Thanking in advance
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Basically, to send a message, you call a method on the Parent object. Depending on what the Parent class is doing, that method might set a boolean member variable (and then the long-running-method would loop conditionally on that variable) or use the interrupt() method of the Thread class, which sets a flag and forces methods like sleep() and wait() to abort with an InterruptedException.

[Jess in Action][AskingGoodQuestions]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
If you're reading one line at a time you don't even need threads

A cleaner way with threads is to schedule a TimerTask to change a variable like stillGoing to false. It might be a little neater for the TimerTask to interrupt the main thread and the main thread to check isInterrupted() instead of a variable.

Finally, if the read might block for a while (I don't know why, but let's say it might) you can try to cause an exception in the main thread. See if this works ...

If you haven't finished reading in 20 seconds and the timer task runs and closes the file see if that causes an exception in the main thread.

Any of those sound fun?

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
I agree. Here's the link:
subject: Notifying a thread event.
jQuery in Action, 3rd edition