Preventing infinite loop in java [closed] - java

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.

Related

Why is Thread.interrupted() not possible to call with Thread.currentThread().interrupted? [closed]

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 2 years ago.
Improve this question
I decided to revise some old multi-threading concepts. I came across interrupt methods. I read about difference between methods isInterrupted() and interrupted(). Point is interrupted() resets the flag, isInterrupted() doesn't.
I started coding and I noticed following. Method interrupted() must be used with 'prefix' of Thread, while method isInterrupted() must be used with 'prefix' of Thread.currentThread(). I wonder why. To demonstrate:
Thread.interrupted(); //compiles
Thread.currentThread().interrupted(); //doesn't compile
Thread.currentThread().isInterrupted(); //compiles
Thread.isInterrupted(); //doesn't compile
To sum, can someone tell me why do they have different calls? And what is difference between Thread. and Thread.currentThread()? I mean when I call Thread. it should directly 'focus' everything to that thread object, so I see no point of using Thread.currentThread() anywhere in Java. Can someone please clear my confusion?
interrupted() is a static method.
For static methods, the usual way to invoke them is like so:
TypeTheMethodIsIn.staticMethod();
contrast this to non-static methods which can only be invoked like so:
(expression of a type of the object containing the method).instanceMethod();
Technically, you CAN invoke static methods in this second fashion, but this is entirely pointless (no runtime lookup is done of the type), and all linter tools, including javac itself, will tell you to knock it off. Which you should heed.
Thread's interrupted() method is static. Thread's isInterrupted() method is not.
The point should be clear enough: Checking the interrupted flag is something you can do to any thread you like. However, clearing it? You can only do that to your own thread.
At some point we're delving into the feelings and thoughts of the programmer of the API on the day they programmed it, to which neither I nor anyone else on SO can give you a reasonable answer. But we can delve into why they MIGHT have done it this way.
Given that you are not supposed to modify the interrupted flag of other threads, only of your own, it COULD have been something like: Thread.currentThread().clearInterruptedFlag(), but now currentThread() is entirely superfluous; attempt to invoke it on any other thread and you'd then have to throw an exception, in order to ensure that a thread can only clear its own flag.
An alternative would be that any thread can clear any other thread's flag, or its own flag, but that is entirely nonsensical. The point of raising that flag is for the code in that thread to eventually stumble across it and exit or otherwise stop some blocking process ASAP.
So why is there no method to easily check your own flag without clearing it?
Again, API design. What point is there to this?
This is how you're supposed to use the interrupt flag:
If the central blocking nature of your thread is based on some sort of CPU freeze operation (defined as: Anything in the core libs that is specced to throw InterruptedException, such as obj.wait, Thread.sleep, yield, etc), you mostly don't have to do anything. If the interrupt flag is raised on your CPU feel free to entirely ignore this; soon (very soon) your thread will execute one of those 'make the CPU freeze' methods, such as Thread.sleep, and the implementations of all these methods first check the flag and will immediately throw InterruptedException without ever even freezing the CPU if they notice that it is raised (and they lower that flag immediately, as well. Either the flag is up, or InterruptedEx is thrown, never both). Which should end your method. (If you are catching InterruptedException and ignoring it, don't do that).
If the nature of your thread is such that it blocks but isn't specced, that it's up to the architecture. For example, if you're waiting on reading data from a network socket, who knows what is going to happen. Either the flag is ignored and there's nothing you can do about it, or, the read() call or whatever you're doing will throw IOException. It can't throw InterruptedException - the method isn't specced to allow that. The flag will NOT be up.
If the nature of your thread is such that the time is spent in active operation, for example, you're mining bitcoin and all you're doing is endlessly spinning that CPU, hashing algorithms together, then out of the box interrupting such a thread does nothing whatsoever. However, such a thread is highly likely to have a while loop of some sort. All you need to do is check the interrupt flag. If it is up, exit. It's up to you how: Either throw something, or, just.. exit. End your #Override public void run() {}'s code cleanly. Hey, you raised that interrupt, you get to decide what it means.
key point for #3 is that in both cases that flag should be lowered, because if it remains raised and your code falls back not to 'this thread is now over' but 'I relinquish control back to my caller', it would be highly surprising if that flag is up.
So, you end up writing code like this:
Runnable r = () -> {
while (!Thread.interrupted()) {
mineNextHash();
}
};
which is short, clean, and to the point. easy peasy.

Lock.tryLock(): Thread performing different tasks? [closed]

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 5 years ago.
Improve this question
I am trying to understand multi-threading in Java, using the
features which were added as part of java.util.concurrent.* . To begin with, there is concept of lock which a thread can try to acquire; if a thread can't acquire, it can do some other tasks.
This I have read in online materials as well in some books, but never ever seen anything they have implemented in real. How is this possible that if a thread can't acquire a lock it can execute other tasks; isn't a thread supposed to do a single "piece of work"? How can it have multiple logic execution based on if it can/can't acquire a lock?
Is there any real implementation which I can refer to see to understand, to reinforce the concepts; else it seems too abstract, how to implement in real life.
Any explanations?
It's difficult to find real life examples because normally you wouldn't design your software to use tryLock(). The example given in the javadoc is as follows:
Lock lock = ...;
if (lock.tryLock()) {
try {
// manipulate protected state
} finally {
lock.unlock();
}
} else {
// perform alternative actions
}
But you wouldn't design your software like that, would you? What if the lock is never (or almost never) available, how will that affect your program? What if it's always available? You have a method that does one of two things depending on pure chance. That's not good design, it increases randomness and complexity.
Okay, so it's not something you decide to use because it's elegant. What is it good for?
Imagine you've inherited a legacy project designed by an insane programmer and it has severe issues with deadlocks. It has synchronized methods peppered all around and needs to be booted at least once every week because it locks up. First you convert all the synchronized methods to use Lock instead. Now you no longer block forever on synchronized, but can use tryLock(long, TimeUnit) to timeout and prevent deadlocks.
Now you've solved the reboot causing deadlocks, but it's still not optimal since you're spending time waiting. With additional refactoring you manage to reduce the locks, but unfortunately you can't do proper lock ordering just yet. Your end code looks like this, where inner locks are acquired with tryLock() or outerlock is released to prevent deadlock:
Lock outerLock = ...;
outerLock.lock(); // Here we block freely
try {
Lock innerLock = ...;
if (innerLock.tryLock()) { // Here we risk deadlock, we'd rather "fail-fast"
try {
doSomethingProtectedByLocks();
} finally {
innerLock.unlock();
}
} else {
throw new OperationFailedException(); // Signal the calling code to retry
}
} finally {
outerLock.unlock();
}
I think the problem is mainly with wording. The Javadoc talks about "actions" (like unlocking an outer lock) being performed based on whether the lock was acquired or not, but it's easy to read it as if the thread would have 2 separate responsibilities determined by the lock state.

Is Thread.sleep() a waste of time for polling in Java?

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.

Stopping a thread that could be looping forever

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?.

Making a J2ME Midlet sleep without threads?

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.

Categories