Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Notifying a thread event.

 
Anirvan Majumdar
Ranch Hand
Posts: 261
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();
timer.start();
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>>...
return;
}
}
}

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
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic