I have a java program that does some calculations and then uploads the results to a MYSQL database (hosted in another computer in the same network). I sometimes face the problem that the program does calculations faster than it uploads the result. Therefore it is not able to upload all the results. The program currently is not threaded.
Is there a way I can make the program sleep for a few milliseconds after it has done the calculations so that the upload takes place properly. (Like in other languages sleep or wait function)
I can thread the program but that will be too much rewriting. Is there an easier way?
Thanks
Is there a way I can make the program sleep for a few milliseconds after it has done the calculations so that the upload takes place properly. (Like in other languages sleep or wait function)
Thread.sleep(milliseconds) is a public static method that will work with single threaded programs as well. Something like the following is a typical pattern:
try {
// to sleep 10 seconds
Thread.sleep(10000);
} catch (InterruptedException e) {
// recommended because catching InterruptedException clears interrupt flag
Thread.currentThread().interrupt();
// you probably want to quit if the thread is interrupted
return;
}
There is no need to implement Runnable or do anything else with thread calls. You can just call it anytime to put a pause in some code.
You don't have to re-thread or any such thing. All you need to do is call:
Thread.Sleep(5000); // pause the app for 5 seconds
Every application is also a thread, in your case also called a single-threaded app. You can use a threading API like Sleep w/o any other code or refactoring.
Big note of caution though: If you need to use Thread.Sleep to manage your control flow then there's probably something going wrong architecturally. From your OP I am concerned than in what you describe as a single-threaded app you seem to have one operation "outpacing" another. This should not be possible, unless you're receiving asynch events from elsewhere.
Another caveat: Sleep takes a millisecond parameter that's usually arbitrary and just means "wait a little while." The problem is that a "little while" may be OK today but tomorrow your machine will be under greater load and "a little while" will no longer be good enough, your Sleep will lapse and the same error will appear. Sure, you can set the time out to "a long while" but then you'll be waiting "a long while" for each and every transaction... Catch 22.
Use Thread.sleep():
try
{
Thread.sleep(1000); // Sleep for one second
}
catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
This does not introduce a new Thread into the program or require any other Thread related machinery.
Just use:-
try
{
Thread.sleep(<time in ms>);
}
catch(InterruptedException ex}
{
}
This will make the current thread (e.g. main thread) sleep.
The static method sleep() in the java.lang.Thread class pauses the current thread -- which could just be the main thread -- when called. You don't need to do anything special to use it.
Every Java application executes in a thread in the JVM. Calling the static method Thread.sleep will cause your application's thread (the one that is running) to stop
Your program is not Multi-threaded...but it is using a thread. Thread.Sleep will still work.
You can use Thread.sleep(); after the calculation without the need to rewrite your whole program with threads!
Related
I'm currently getting familiar with threads and multithreading in Java. I'm doing a simple exercise where I have to split the array into equal partitions based on N number of threads that I pass to my function at run time.
However, I'm curious to know if I'm actually executing mergeSort() in each thread, or is it just running as a single thread. I did a for loop, and it was something like Thread.start() followed by a try-catch block, where Thread.join() would be called and then I would print the name using Thread.currentThread(). However, I get the word "main" throughout the entire execution.
Does this mean I'm not really multithreading? My thinking would be that I'd get something like Thread-0..., but I only get that if I do Thread.getName();
Please advise.
for (MedianMultiThread mmt : threadList) {
mmt.start();
try {
mmt.join();
sortedSubArrays.add(mmt.getInternal());
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
EDIT: Realized that I was running currentThread() in the thread, but when I ran it in the run() method, then I got different results. Thanks everyone!
The name thread.currentThread() method confuses a lot of people. thread.currentThread() does not return the "current thread" unless you happen to think that "current thread" means, the thread that calls the function.
That's what thread.currentThread() actually does: It returns a reference to the thread that called it. If it's always returning "main" in your program, then that means that your program only ever calls it from the main() thread.
The name comes from a long time ago when most computers had only one CPU, and it was supposed to mean something to the guy who was writing the thread scheduling code. If you're writing the scheduler for a single CPU machine, then there can never be more than one thread running at any given time. It's natural to call it "the current thread."
The system call that returns the identity of the current thread in an old-school-Unix-style operating system running on a single CPU system could only ever return the identity of the thread that called it.
That turned out to be very useful in user-space programs.
The idea of a "current thread" doesn't mean much on modern multi-processor systems, but a system call that returns the identity of the calling thread still is every bit as useful as ever.
Unfortunately, we're stuck with the old name for it.
P.S., This never makes any sense:
mmt.start();
try {
mmt.join();
...
} catch (...) {
...
}
There's never any reason to have two (or more) threads unless they can both do something useful at the same time. In your code example, one thread starts a second thread, and then the first thread does nothing except wait for the second thread to finish.
You might just as well have done all the work in the first thread.
Try this:
You need to actually start all threads, then join them all back together,
// start all of them
for (MedianMultiThread mmt : threadList) {
mmt.start();
}
// join all back to main thread
try {
mmt.join();
sortedSubArrays.add(mmt.getInternal());
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
// ... inside your worker thread's run() method
public void run(){
System.out.println("Thread: "+Thread.currentThread());
// do actual work...
}
You have to check in your code, whether function Thread.currentThread() is called from the actual executing worker threads (and not from the main thread). This means, you need to put your Thread.currentThread() output inside the run() methods of the sort-worker threads.
Second advice is that threads are running randomly. I don't think that's the issue, but you need to keep that in mind.
It it is always printing "main", this means that the piece of code which is printing the name of the thread is executed by main thread always, and so that piece is not multithreaded. It would have been better if you had shown the exact code.
I came across some Java code that has a method containing the following:
static boolean waitForSeconds(long seconds) {
try {
Thread.sleep(seconds * 1000);
} catch (InterruptedException ex) {
return false;
}
return true;
}
What might be the purpose of this? The return value is used to determine whether a computation should continue. It seems strange to me to try to sleep for 1 second for the sole purpose of checking whether the thread was interrupted during that second.
Is the code that calls this method trying to accomplish the same thing as thread.isInterrupted()? Whatever it is trying to do, is there a better way?
The call to waitForSeconds appears at the top of another method, not inside of a loop, so if this code does intend to wait for a second for some purpose in addition to checking for an interrupt, it seems like it would be checking in the wrong place. Wouldn't it be better to put the sleep near the loop, where it is clearer what it is doing?
For the last question, please reply here instead:
Is it clearer to sleep near a function call in a loop or in the function call itself?
The purpose is to pause.
Check the code calling the outer method to try to see why they want to pause.
They may want to save CPU or network.
The purpose of the method is to cause the thread execution to stop for the specified number of seconds. The catch clause allows the method to communicate to the caller that the thread was interrupted, as opposed to the time period expiring.
The idea is probably to introduce a pause in the computation, but if the pause is interrupted, then that means that the computation should not continue. Why a pause is needed is impossible to say without seeing the surrounding (calling) code.
I guess they want to pause for at least x seconds; if for some reason the Thread was unable to sleep that long, they'd use the return value to call the method again
I never gave the use of Thread.Sleep much thought, until I downloaded the latest version of Netbeans. Netbeans now warns you not to use Thread.Sleep. So I did some research on the topic and found people stating that you only need to use Thread.Sleep for debugging/testing purposes and that if you use it at any other time you have poorly written code.
So my question is how can I keep from using Thread.Sleep in the following situation.
I have written a server application that interfaces with another application. The server has two threads:
Handles the data coming over the socket and sends back other information or just plain acknoledgements.
This is the main thread. After kicking off the socket thread it going into an indefinite while loop. Within this while loop I check to make sure the socket thread is still active and that the user hasn't asked to exit the application via a TrayIcon interface. Then I sleep and continue this while loop.
With this application, the TrayIcon is the only UI.
Here is the snippet I'm referencing:
// continues running as long as the exitth file is not present and
// the tray icon is not in a safe to exit status.
while(doNotExit())
{
if (getPrimaryThread() == null || !getPrimaryThread().isAlive())
resetsThreadAndSocket();
try
{
// check to see if the socket threads are still active, if not create new ones.
if ((getPrimaryThread() == null || !getPrimaryThread().isAlive()))
createSocketThread();
// check right before sleeping that the user does not want to exit.
if(getTrayIcon().isExiting())
break;
// puts the main Thread to sleep for 3 seconds
Thread.sleep(3000);
}
catch(SQLException ex)
{
_log.error(ex.getMessage(), ex);
restartDatabase();
}
}
The 'preferred' method in most cases would be to use the ScheduledExecutorService built into JavaSE for performing a periodic task, rather than reimplementing it yourself every time using a while loop and Thread.Sleep().
There's nothing wrong per-se with your example. The language just now has a much more robust support for doing that built into it as of Java 5.
Instead of your Thread.sleep(3000) do:
getPrimaryThread().join(3000)
This will wait for the thread to exit for 3 seconds.
You should consider attaching an event listener to your tray icon instead of polling its state. That way you won't need an extra thread just for monitoring.
If you can't do that for some reason, you can still do away with the extra thread as the Timer class can do the waiting for you.
You seem to be paranoid that some condition (maybe a RuntimeException or Error?) is going to cause your socket Thread to just die. Ideally, you would design your Socket Thread such that it protected itself from crashing. The following example creates a loop that can only be broken as a result of a JVM Error or Thread interrupt:
public void run() {
while(!Thread.currentThread.isInterrupted()) {
try {
//you application logic
} catch (RuntimeException e) {
//log uncaught exception
}
}
}
In order to shutdown the application, you would attach a listener to the TrayIcon which contained a reference to the SocketThread and could stop it by simply interrupting it.
socketThread.interrupt();
I'll leave figuring how to add an ActionListener to a TrayIcon up to you.
I have a complex function (optimisation) that can potentially enter in a loop or just to take too much time, and the time allowed is set by the user.
Therefore I am trying to make to run the function in a separate thread, and to stop it if the maximum time is passed. I use a code similar to the one below, but it doesn't work, so
int timeMax = 2; //time in minutes
Thread Thread_Object = new Thread_Class(... args...);
try {
Thread_Object.start();
Thread_Object.join(timeMax*60*1000);
}
I think that I'm not using the function "join" properly, or it doesn't do what I have understood. Any idea?
Thanks!
Thanks for the answers, currently I have found a better idea here*. It works but it still uses the function "stop" that is deprecated. The new code is:
Thread Thread_Object = new Thread_Class(... args...);
try {
int timeMax = 1;
Thread_Object.start();
Thread.currentThread().sleep( timeMax * 1000 );
if ( Thread_Object.isAlive() ) {
Thread_Object.stop();
Thread_Object.join();
}
}
catch (InterruptedException e) {
}
not yet sure of the function of "join", I'll have to go to have a look at some book.
java scripting API - how to stop the evaluation
I suggest you use a Timer.
The join method will wait the current thread until the thread that is being joined on finishes. The join with milliseconds passed in as a parameter will wait for some amount of time, if the time elapses notify the waiting thread and return.
What you can do, is after the join completes interrupt the thread you joined on. Of course this requires your thread to be responsive to thread interruption.
Thread.join(milis) does not kill the thread. It just waits for the thread to end.
Java threading is cooperative: you can not stop or gracefully kill a thread without it's cooperation. One way to do it is to have an atomic flag (boolean field) that thread is checking and exiting if set.
Watchdog-Timers in Java are not a simple thing, since threading is cooperative. I remember that in one project we just used Thread.stop() although it is deprecated, but there was no elegant solution. We didn't face any issues using it, though.
A good example for a Java Watchdog implementation:
http://everything2.com/user/Pyrogenic/writeups/Watchdog+timer
This might be useful
http://tempus-fugit.googlecode.com/svn/site/documentation/concurrency.html#Scheduled_Interruption
Quick question ... Using J2ME (CLDC 1.1, MIDP-2.1) is it possible to sleep the Midlet for a period of time (not using threads)... For example:
public class myMidlet extends MIDlet{
public void startApp() {
/* Sleep for 10 seconds */
/* The answer was: */
try {
Thread.sleep(time_ms);
} catch (Exception e) {}
}
...
I don't use Java all that much, and don't want to program threads just for a simple sleep.
Thanks in advance
Answer Summary
My lack of Java knowledge. Examples I saw using Thread.sleep() led me to believe it was only usable in a thread object spawned by the Midlet ... not the midlet itself. I didn't want to have to spool off the midlet logic into a thread to sleep it ... But now I know the midlet runs in the default thread :) Going to find that Java book I never read because I didn't think I would use the language ever
I didn't understand whether you mean putting midlet in paused state or just stopping execution for specified time.
If it's the latter, actually I don't undesrtand, why you don't want to use Threads, this is no big deal. You just insert three following lines wherever you need:
try {
Thread.sleep(10000);
} catch (Exception ex) {}
That's all, nothing too complicating.
I don't know the exact answer, but I also don't understand what's the problem with calling static method Thread.sleep(milliseconds) that "Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds" . Do you call this programming threads?
I would go for Malcolm's approach since your thread may possibly throw an exception.
[...]and don't want to program threads
just[...]
Uh, you'll have a hard time programming J2ME and trying to avoid threaded programming. If your app becomes just a bit more complicated, especially when using network connections you'll have to use threads. Moreover if some operation takes more than 2-3 seconds it's highly advisable to run it in a separate thread, possibly (contemporaneously) notifying the user about the ongoing work.
Btw, what I forgot. I've recently written a J2ME application for a university course. There I've constructed what I called "ExecutableTask" which allowed me to handle threads in a convenient and easy way. If you want to have a look at the source...Unfortunately you cannot browse it online in the Google repository due to some bug of Google's hosting solution (some name of my project my cause this).
You can try using Object.wait(), Object.wait(long timeoutValue). Although I would not advise you to try and delay the main startApp() / system thread.