aspose file tools*
The moose likes Threads and Synchronization and the fly likes basic concept level question regarding threads Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "basic concept level question regarding threads" Watch "basic concept level question regarding threads" New topic
Author

basic concept level question regarding threads

Patrick Brahami
Ranch Hand

Joined: Oct 12, 2008
Posts: 32
I'm kinda new to java and threads. I know the syntax but I'm not sure concept wise how to implement what I want, although I'm sure it's simple.

I'm making a program and I want to time an action.
Someone enters 'tuesday 25/10/08 8PM' for example, and I want to perform action on that date.
Now, with the Date class and such I can figure out if it's the current date, but how do I do it exactly, will I have to compare dates each what? second?mint?hour? How is it done?

In addition, as I see it, I believe I have to open a thread for my main program, and another for the program that compares current date and input date. Am I correct here?

Any help will be appreciated.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi,

Welcome to JavaRanch!

First, a bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. A single nonsense word is not sufficient. You can change your display name here. Thanks!


[Jess in Action][AskingGoodQuestions]
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

You should read this tutorial: Java Concurrency.

There are a number of ways to implement what you want to do. You say that you have an event to occur at some specified date, then ask how often you have to check. This assumes you are using POLLing method to check for the event - essentially you have the event, and every so often you check current time with the target time, and if it is the same +/- some nearness factor than execute the event. When Polling, you have to decide how accurate your timing needs to be. If you need the event to occur at the exact millisecond defined, then you will have to poll every millisecond. If 'close enough' is in the same minute as the target date then pool in minute intervals.

But the second way to do it would be to force the thread to sleep until the proper time. Instead of Polling, you are scheduling. For example:


This blocks the thread, so each event would need its own thread - if you have a lot of events this can be significant overhead, but the execution should be quite precise. Using Polling you can get away with one execution Thread, which will cost less memory, but to reach the same precision would require a lot of Polls, so your cost comes in the form of consumed CPU cycles.

There are built-in tools that will help you out and safe some of the cost. One tool is the ScheduledExecutorService, which controls a number of threads for executing events, plus one for handling the scheduling. It does this for you, all you do is tell it what task to run (in the form of a runnable), and how long to way (with a TimeUnit to help define your precision).


Look at the tutorial I linked to for more details on the classes I used. The Tutorial has links to the API as well.


Steve
Patrick Brahami
Ranch Hand

Joined: Oct 12, 2008
Posts: 32
First of all I'm sorry about the name, consider it fixed. [I thought my login name is the one that appears, so didn't put much effort into the first/last name]

Second of all, I think I understand the two approaches you mentioned.
I can use scheduling since I know what time it is now [getting the input time and date] and I know when is the target date, so I can calculate how much time left and tell the thread await that time. Looks like a nice way.

Polling was the first thing in my mind, although it looks messy now that you mentioned the other way to do it.

So it comes to the question you raised yourself- what is less CPU consuming?
I mean, at one approach I have many threads sleeping, in the other I'll have one thread checking time every ~15mints.
In my case, I'll have many events pending, and accuracy is not so important. [I can suffice with 15mints, even each 30mints]

Elegance-wise the first approach sounds better to me, any way I can find CPU difference between the two approaches?

Oh, and hey indeed javaranch!
[ October 12, 2008: Message edited by: Patrick Brahami ]
Patrick Brahami
Ranch Hand

Joined: Oct 12, 2008
Posts: 32
Follow up questions, please aid me.
By now I've looked into the classes of java regarding my matter.
Timer and TimerTask, even though not the most sophistcated out there fits perfectly for me.
Now, as I understand if I create timer.schedule(new someclass, mydate);
while myDate is a Date object, the schedule method will start someclass.run() method at that time.

I have two issues:
a] How do I set up a date object to a specific date? as I see it only has get methods, and most of them are deprecated anyhow. And I have to use Date since timer.schedule requires a Date object.

b] timer.schedule starts a thread behind the scenes I assume. but how does it operate? how does it know when the written date arrived?


Thanks in advance.
[ October 13, 2008: Message edited by: Patrick Brahami ]
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

Originally posted by Patrick Brahami:
So it comes to the question you raised yourself- what is less CPU consuming? I mean, at one approach I have many threads sleeping, in the other I'll have one thread checking time every ~15mints.
In my case, I'll have many events pending, and accuracy is not so important. [I can suffice with 15mints, even each 30mints]

Elegance-wise the first approach sounds better to me, any way I can find CPU difference between the two approaches?


Having a thread sleep will not cost any CPU cycles, so it is lighter on the CPU and other things will run faster. On the other hand, you have a lot of tasks, so they will consume a bunch of memory. How much you would have to test, but a pure Scheduling theme would not scale well in your case - which is why I mentioned the ScheduledExecutorService (and Timer/TimerTask solves this as well). If you have many objects and 15 minute poll frequencies then you would lean closer to the polling method since you would not be consuming a huge amount of CPU cycles and limiting the number of threads created (that is, if you were writing your own scheme).

Timers (and ScheduledExecutorServices) use a single thread and act basically as a combination of polling and the scheduling approach I described. Tasks aren't Threads themselves, but are run inside threads controlled by the Timer/Executor. They use a collection that sorts the tasks for the shortest delay, it then blocks the scheduling thread until the shortest time period comes up. When the thread wakes up it pulls the current task out of waiting and then runs it. With Timer/TimerTask it runs the task in the same Thread as the scheduling occurs, so you get one task running at a time. While in the ScheduledExecutorService you have one scheduling thread and a user-defined number of execution threads, so you could have multiple events triggered at the same time.

I would suggest using either the Timer/TimerTask approach or the ScheduledExecutorService approach, they both scale very well. I personally use the ScheduledExecutorService because it is more flexible, but in the end it is a matter of which is easier for you to use.
[ October 13, 2008: Message edited by: Steve Luke ]
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

Also, for your Date question. The best way to get a date for a specific future (or past) time would be to use Calendar.

Would set the target day at October 14, 2008 at 4:30pm.
Patrick Brahami
Ranch Hand

Joined: Oct 12, 2008
Posts: 32
Once again thanks for your detailed post.
You solved my Date issue.(Eclipse mentioned it, but I didn't know it has a method that returns Date object)

Now, regarding Timer/TimerTask versus ScheduledExecutorService
I've created a Class that creates a Timer and TimerTask for my usage for each event I want to schedule.
Is it the wrong way to do so? Could I with ScheduledExecutorService somehow use one taskmanager for all my tasks? And is it better design-wise, time-wise, or both ?

Once again, thanks in advance.
[ October 13, 2008: Message edited by: Patrick Brahami ]
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

You can (and should normally) have one Timer with many TimerTasks that run. ScheduledExecutorService would behave the same way. You set one Executor and schedule many events with it - but instead of TimerTasks you use Runnables.

Really the only reason I like the Executors is because they are more integrated with the new java.util.concurrent package and because the ScheduledExecutorService allows me to run a ThreadPool which would allow multiple events to run together if they have to. If your system doesn't require simultaneous execution then you would be just fine with the Timer/TimerTask system.

But I would make sure you have 1 Timer and schedule n TimerTasks (where n == number of events).
Patrick Brahami
Ranch Hand

Joined: Oct 12, 2008
Posts: 32
More Follow up question.

This time I've got a design problem.
I want to execute some code right after a scheduled event takes place.
Now all the options I can think about are not so elegant.
First option I have in mind is adding the code into the TimerTask of the other event, but the two are different logic business, I wouldn't want to bind them together in a same TimerTask.

Second option I think of is scheduling in a different TimerTask the other event for a little later.
But that won't cause the code to happen right after necessarily from what I understand. [because of JVM / Garbage Collection issues]

Is there a more elegant way to do this I don't know about?
[ October 14, 2008: Message edited by: Patrick Brahami ]
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

Originally posted by Patrick Brahami:
More Follow up question.

This time I've got a design problem.
I want to execute some code right after a scheduled event takes place.
Now all the options I can think about are not so elegant.
First option I have in mind is adding the code into the TimerTask of the other event, but the two are different logic business, I wouldn't want to bind them together in a same TimerTask.

Second option I think of is scheduling in a different TimerTask the other event for a little later.
But that won't cause the code to happen right after necessarily from what I understand. [because of JVM / Garbage Collection issues]

Is there a more elegant way to do this I don't know about?

[ October 14, 2008: Message edited by: Patrick Brahami ]


I wouldn't want to schedule the second event as a TimerTask. Events in the Timer should be relatively un-linked, not depending on each other for order of operations.

You should call the new code directly from the end of the TimerTask. You don't have to include the code in the same class, you would put the code to run in a sister class that you would call from the TimerTask when it finishes. One of the ways to help decouple the two would be to create an interface and make your second event implement this interface. If you haven't guessed already, my preference would be to use Runnable:
Carey Evans
Ranch Hand

Joined: May 27, 2008
Posts: 225

A second option is to create a new class that extends ScheduledThreadPoolExecutor and overrides the afterExecute() method. I can't say whether this suggestion or Steve's is best for you without knowing more about the problem.
Patrick Brahami
Ranch Hand

Joined: Oct 12, 2008
Posts: 32
I see. Once again problem solved, thank you!

Got more follow up questions, hope they're last ones, this time abit unrelated for I'm at the final stage - GUI, and I'm trying Swing and Netbeans GUIBuilder for first time. [Usually it's SWT &Eclipse]

So I've got some technical questions, hope you could help me with.
My program downloads something from the web, and I give it only a name of file - and it automatically stores it in a default directory, the NetBeansProject one, inside my current project.
What will happen if I export the program? will it save it in the program folder?

If so, is there a way to acquire that default root as a string somehow?
for I use run.exec(openingSoftwareLocation,/s ,filetoOpenlocation)
and I want to enter the location of the currently downloaded file.
I tried adding a relative path to the command too, but it doesn't work.
Is there a way enter a relative path to the filetoOpenlocation?
or can I retrieve the default directory as a string somehow?


Oh and last thing, is there a way to close a form without .dispose()?
Because I have my main form, with an inner class of another form in it.
When I open that form, and execute dispose method, it closes both forms for some reason.
Even if I click this.dispose() within the inner class(which is a JForm) it closes the main form. Why is that? How can I refer to my inner class object from within it?
Oh, also, even the windows 'X' sign of the new form closes both form. Weird.
Once again - thanks in advance!

[ October 16, 2008: Message edited by: Patrick Brahami ]
[ October 16, 2008: Message edited by: Patrick Brahami ]
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

Originally posted by Patrick Brahami:
I see. Once again problem solved, thank you!

Got more follow up questions, hope they're last ones, this time abit unrelated for I'm at the final stage - GUI, and I'm trying Swing and Netbeans GUIBuilder for first time. [Usually it's SWT &Eclipse]


I am no swing/GUI expert but I will try and help. You might want to ask again in the Swing/GUI forum to get more reliable answers.


Originally posted by Patrick Brahami:

So I've got some technical questions, hope you could help me with.
My program downloads something from the web, and I give it only a name of file - and it automatically stores it in a default directory, the NetBeansProject one, inside my current project.
What will happen if I export the program? will it save it in the program folder?


If you specify a relative file name then it will save to the user directory, which is whatever path is the active path when Java starts - system dependent. You should probably try to control this using an absolute base path if you can.


Originally posted by Patrick Brahami:
If so, is there a way to acquire that default root as a string somehow?
for I use run.exec(openingSoftwareLocation,/s ,filetoOpenlocation)
and I want to enter the location of the currently downloaded file.
I tried adding a relative path to the command too, but it doesn't work.
Is there a way enter a relative path to the filetoOpenlocation?
or can I retrieve the default directory as a string somehow?



The default root is stored in the "user.dir" property. You can get it using System.getProperty("user.dir") and set it when the application starts (so you know where the file is going without worrying about shortcut location, or whatever) using java -Duser.dir=/absolute/path <rest of app startup command>.


Originally posted by Patrick Brahami:
Oh and last thing, is there a way to close a form without .dispose()?
Because I have my main form, with an inner class of another form in it.
When I open that form, and execute dispose method, it closes both forms for some reason.
Even if I click this.dispose() within the inner class(which is a JForm) it closes the main form. Why is that? How can I refer to my inner class object from within it?
Oh, also, even the windows 'X' sign of the new form closes both form. Weird.
Once again - thanks in advance!



This is the part I have no real clue about. You might beIn the Swing/AWT/SWT/JFaces Forum. able to hide the form using .setVisible(false) or use setDefaultCloseOperation(HIDE_ON_CLOSE) if the JForm is a subclass of JFrame or has similar methods. Again, maybe better asked
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: basic concept level question regarding threads