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.
Related
I am facing an issue that when I run second instance of my application on the same port - I am getting SocketException: java.net.BindException: Address already in use: bind
The problem is that after getting this exception my application continue running.
After some hours I have noticed that (using "Get thread dump" tool) there are some threads still alive even after main is died.
I don't have access to that threads that means that I am not able to design it in way that I can interrupt them properly
Also, thread.interrupt, thread.setDaemon(true), thread.stop - nothing helped me.
How to stop that threads?
I am working on very big legacy application and threads that I want to stop are created in library that I don't access
You cannot forcibly stop threads in java. The thread has to work with you: It needs to have a core loop that looks a bit like this:
while (running && !Thread.interrupted()) {
// do something that won't take long.
try {
Thread.sleep(1000L); // or some other 'wait a while' code.
} catch (InterruptedException e) {
return;
}
}
If the code of the thread doesn't have this, and you can't change it, there's not a lot you can do about it. Thread.stop does not work on modern javas because that 'model' (throw a particular exception inside the thread, where-ever it is right now) is just something that makes for buggy software (because locks and such are unlikely to be properly closed and such): Therefore it has been deprecated for a decade now and no longer works at all. Even if it did, a thread can prevent you from stopping it.
Which leads us to the one surefire way to definitely, absolutely, kill a thread:
System.exit(0);
that'll do it. It is a common misconception that 'nice' code style is to never forcibly exit like that, with the right style being to tell all (non-daemon-status) alive threads to clean up their business and exit.
This is mistaken. Just exit. Your code should be written not to need to do any cleanup of resources, because if you write it like that, it means if someone trips over a powercable or java is hard-killed, your app just created a mess. The few cleanup jobs you do have should be registered as shutdown hooks.
So, if you want to quit the VM, just System.exit.
Of course the very first thing to do is to try and fix the other side of the code. If you can't do that and at the same time you can get a hold of those threads - you could call interrupt on them; and again, hope that the person that wrote that code knew how to handle those interrupts.
Otherwise, you are completely out of luck, unless System::exit is an option and a restart I guess. But again, this is not really your problem that some other resources, out of your control, do not clean up after themselves.
Even if they do respond to interrupts, what if you leave your database/file manager/whatever in a corrupt state?
Suppose I have a nametag, which is UI component in GUI program.
The nametag will constantly change its text based on the data.
If the user change his/her name data, then he/she will see the change in nametag.
For this task, my code looks like this:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
String name = data.getName();
nametag.setText(name);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Since the reaction time of 0.1s seems instant to people, I included Thread.sleep(100) for computer to take a break.
However, I am not sure if that helps the computer in terms of energy usage or something. Is sleep method in this case complete waste of time? No benefit at all?
Thread.Sleep has been used for many things it shouldn’t be used for.
Here’s a list of the common mistakes:
The thread needs to wait for another thread to complete
In this case no value, other than infinite, passed to Thread.Sleep will be correct. You simply don’t know when the other thread will complete using this method. If the thread completed after Sleep returned you’ll likely have synchronization problems. If the other thread completed before Sleep returned the thread was needlessly blocked for an amount of time rendering the benefits of multithreading limited or moot. In the control circumstances where you’ve tested this it may seem like it always works; it just takes a busy program to cause it to faile: a defrag program, a sudden influx of network traffic, a network hiccup, etc.
The thread needs perform logic every n milliseconds
As noted earlier, Sleep means relinquish control. When your thread gets control again isn’t up to the thread; so it can’t be used for periodic logic.
We don’t know why Thread.Sleep is required; but if we take it out the application stops working
This is flawed logic because the application still doesn’t work with Thread.Sleep. This is really just spackling over the problem on that particular computer. The original problem is likely a timing/synchronization issue, ignoring it by hiding it with Thread.Sleep is only going to delay the problem and make it occur in random, hard to reproduce ways.
Source: http://blogs.msmvps.com/peterritchie/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program/
This doesn't answer your direct question, but it does help address an XY Problem component of your question:
It looks like you're listening for object state changes by polling: by constantly testing an object to see what its state is and whether it's changed, and this is a bad idea, especially when coding for an event-driven GUI. Much better to use an observer pattern and be notified of state changes when or if they occur. That is how the Swing GUI library itself was written, and you should strongly consider emulating this.
Some ways to be notified of changes are to use component event listeners which can listen for changes to Swing components, such as ActionListeners, ChangeListeners, ItemListeners, and the like. Another way when listening to non Swing component items is to use SwingPropertyChangeSupport and PropertyChangeListeners and in this way to create "bound" properties of your class. This is often used for non-GUI model classes.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I wanted to make a little game like robot wars in Java.
the idea is to extend my class Robot, with the custom rules, you add to it.
however, i have so things I want to prevent coders to do, like infinite loops.
I know some compilers will complain if there is an endless loop, in a Methode the requires a returning value. but I don't think all compilers will return an error on this, so I was thinking if there was a way to check this another way too?
or maybe a way to make some sort of timeout on a method?
Update:
Looking back to this question I posted almost 3 and a half year ago, I am no longer doing programming in Java, however still an active Programmer, and with the years, I learned how hard it is to police 3rd party code if there is no review cycle implemented.
There is no simple way to check if Code is malicious (that is why we have anti-virus programs).
To do a thing that I wanted to do, I first of need to control the entire platform I am developing too, to check for reasons the code is behaving as it is, a task that would be nearly imposable or too time-consuming.
that is why to do this more securely, the solution I reached is to use a Scripting Language that limits the user to the idea you had in mind.
Hosting a Program on servers, that everybody has access to add code to is simply not a good idea. not even with Manage Program Languages as Java and CIL, as the platforms are not checking for those specifics, it would simply take too much effort to do this.
Even though there is a way to "Sandbox" programs in Java, by using Policies
and C# have something similar, it would never prevent a skilled programmer to exploit or do something that was never intended.
I hope this update gives other a warning to what they are doing since I noticed this topic recently go searched a lot.
I'm not sure I understand the context of the game. But I would like to begin this answer by saying that you cannot prevent someone from coding an infinite loop, and you cannot stop an infinite loop once it is running. As long all your code is reachable, and you return what you have to etc., Java won't help you in detecting and preventing infinite loops.
However, if you would like to execute another routine for a period of time and ensure you get access to your thread again, one way to do so is through a Future.
If you allow "other coders" to implement a Runnable or a Callable, then you can use the Future class's get(long timeout, TimeUnit unit) method to cause the robot to timeout after a predetermined period of time. This will prevent infinite loops in the other thread from claiming your thread forever.
However, it is important to note that if the other Robot has an infinite loop, it may never stop running even after your timeout. Java provides no guarantee that it can stop the other thread. So when invoking such routines in your code, it is important that you know what you're invoking.
Here is some sample code which uses a Future.
abstract class Robot implements Runnable {
}
class SampleRobot extends Robot {
#Override
public void run() {
while (!Thread.interrupted()) {
}
}
}
class RobotRunner {
ExecutorService executorService = Executors.newSingleThreadExecutor();
public void runRobot(Robot robotToRun) throws InterruptedException, ExecutionException {
Future<?> robotFuture = executorService.submit(robotToRun);
try {
robotFuture.get(5, TimeUnit.SECONDS);
} catch (TimeoutException e) {
// This is where you would handle the timeout occurring.
}
}
}
Remember that you should not expect real-time behavior from timeouts in Java. Also remember to shutdown your ExecutorService when you're done using it.
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!
I have a program where I compile java code a user types into a text field, and then run it. A run the code in a seperate thread, so that the GUI they use to input the source code doesn't get locked up.
The GUI has an abort button that should stop the thread. My issue is that I need to stop the compiling thread no matter what is going on inside of it, which means I must account for a case where the thread is caught in an infinite loop (due to user error), and it cannot properly end itself using a safe flag. I've read up on many solutions that involve using a flag of some kind, but they aren't available to me because of this looping issue. I need to have the thread stop and the memory it's using freed (I can't just let it sit in the background forever, unless that is the only solution left). Any advice or alternative solutions? Hopefully some fresh perspectives could help squash this issue.
Edit:
Here's a sample bit of user submitted code:
public class RunMe extends SomethingThatRuns {
public void run() {
int i = 0;
while (i = 0) {
//Prepare to get stuck!
}
}
}
I'll compile this class, and then run it. This is where it will get stuck, and the run() method can never finish, or even loop to check a flag.
You can run it in a new JVM so you can kill it when you want.
Thinking about security this may be a good thing to do too.
Call stop() on the thread.
Yes, this is a deprecated method. However, it really shouldn't be "deprecated", it should be "dangerous." In some circumstances, however, there's really no choice but to use it, and the invocation of an "agent" provided by a user is one of those cases.
Make sure that your program doesn't use any data that are manipulated by this user thread; or, if you do, devise some transactional mechanism to exchange data safely between the threads.
Even this method isn't guaranteed to terminate the thread. For example, the user can catch the resulting Throwable and ignore it. Or, the thread implementation might not respond to stop() calls if the thread is in some native code. But it's your best chance.
The core issue here is the fact that the code even allows an infinite loop to be entered as part of user error. Fix that, and everything else will become easier to deal with.
Properly-behaving threads should usually terminate themselves gracefully when there's no work to do (or return quietly to a thread pool to ask for more work, if that's your application's design). If you feel like you need to have one thread forcefully kill another then you've likely got a fundamental design issue. It's fine to have one thread tell another, "Hey, you should terminate now so that I can join with you..." because that allows your threads to clean things up as they finish. Forcefully destroying threads just isn't the right way to manage these situations.
You can use them to insert a interrputed check in every loop and maybe in other places too.
I can see two options:
As you compile the user code you can edit it before. You may use
ANTLR to parse and modify the code.
There are bytecode manipulation frameworks like ASM that allow you to manipulate code that is already
compiled.
I don't think it is easy but it might be a way.
interupt(); the Thread in the gui
and in the code that the thread runs regularly check for Thread.interrupted() and throw an exception when you do especially inside loops
At a high level, you are asking how one thread might go about stopping another thread. To that end, see this SO question Stopping a Thread in Java?.