Pause/Resume arbitrary computation in thread - java

I'm making a programming game where the player can program their allies' behavior. The player writes the body of the decide() function for a given ally, which can be filled out with any java code but has to return an action. I would like to give each ally a set, restricted amount of computation per tick so 1) adding more entities doesn't slow down the game too much, and 2) The time an entity spends computing is reflected in game, so if an ally spends more time "thinking" it will act less often. My inspiration for how this should work is Battlecode, which gives units a set amount of bytecode per turn, then just pauses the computation and makes the programmer deal with noticing when things have changed.
My question is how I can pause and resume an entity which is executing the decision function in a thread. I understand the 'proper' way to do this is to set a flag telling the thread to pause and have it check occasionally, but since I can't force the player to check for a flag within the decide() function, I'm not sure how to pause the thread. The entities are only looking at a fixed representation of the world and just have to return an enum value, so I don't think they should have locks on anything, but I'm hoping there's a better way to do this than using the deprecated thread pausing methods. I'm open to changing how the player has to write code, but I can't think of a way to do it while still hiding the pause flag checks from the user without making writing the decision loop confusing and onerous. There must be some way to do this, since Battlecode does it, but I'm at a loss searching online for details as to how.

If you want to 'pause' the current thread, java.util.concurrent.locks.LockSupport may helps you. If you want to pause other threads, I thinks it's not in the scope of java design, you can only interrupt another thread, or set a flag, not pause.

You can't "pause a thread", and you can't expect players to abide by your request to "play nice" and check for flags etc. You can interrupt another thread, but the code running in the thread can easily recover from this. So, you need a way for the controlling thread to retain control.
Instead of worrying about what threads are doing, you could:
give the player threads a maximum time to return the action, and if they don't return in time, execute a "default action"
keep a record of how much time they spent calculating and call them more often is they use less time etc
Most of these types of concerns are catered for by java.util.concurrent library. Check out:
ExecutorService
Executors for creating handy instances of ExecutorService
Callable for what the players will implement
Future for getting the result, especially Future.get(timeout) for limiting the time the thread has to return a result

Related

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.

Minimum time to sleep to ensure sleep occures regardless of clock cycle?

I know clock cycles vary between operating systems and settings. If I am writing code that wants to be relatively confident (at least 95% sure) of a sleep occurring what is the minimum time I could use for a sleep and be confident that any computer/os running the code will sleep?
Is there a way to gaurente a sleep of at least one 'clock cycle' regardless of how long that cycle is in java?
You should never try doing that. Ask yourself if you really need to sleep for one clock cycle. Tying your implementation with timers is always a bad decision. Below I give you a few alternatives.
Use a mechanism similar to fps in games implementation
A number of libs already implement the concept of fps. Usually their implementation already abstract away clocks per second and OSes limitations/details. You could use that concept and be platform agnostic.
This way you can tweak your time requirement by using more or less fps.
Use a mutex.
Why do you need to sleep for one cycle? That is a very small amount of time. You could try to synchronize (if that is the case) using mutexes instead of timers.
Also, mutexes are usually implemented by hardware instructions. So that guarantees they are atomic. If you really need to sleep for an infinitesimal time, you could lock the mutex and then unlock it. To be honest, any code you execute will by definition (unless it is a NOOP) be similar to sleeping by one cycle. You could also use tmp = 1+1. That takes two instructions.
I suggest the mutex. From your question, it is not clear why you need that sleep time.
Mutex with user interaction
If you need to wait for user interaction (or any external event, like requests), lock the mutex and only unlock it when the event or user input becomes available.
Derive the timer value
If you really wanna go down the timer road, I suggest you implement a routine that executes a long for loop and then you can try to derive your timer from the time it took to run through that for loop.
As I said earlier, I don't find this approach to be reliable but it is something. Also, I suggest that you also protect this code using a mix of Monte Carlo reliability techniques and unit tests. You can read more about this on this article.
As a final note, beware the optimizations that the compiler/interpreter can make and screw your timer.

Make something wait without using Thread.sleep()?

I am trying to make an intro to a game with some strings that I want one to wait for another to pop up, and I don't directly want to use Thread.sleep() for it to wait, because I am not sure if that is the best option. Is there any other way to make something wait than making the thread sleep, or will I just have to make the thread sleep?
If this is a game you shouldn't use sleeps or timers.
Typically games have their own internal clock mechanism. This means you will try to render the frames as fast as possible. Your OnRender method will be invoked with the current time of the game. You can use this to determine if enough time has passed to go to the next screen.
This means you will be given a point in time A in frame 1. You'll be given the Delta or another point in time B in frame 2. You can determine how much time has passed by using the delta or calculating the delta yourself. This is a very efficient mechanism for timing situations and worked quite well when games were single threaded. The idea of any program is to never block for anything.
The reasons things typically block is due to I/O such as reading from disk, the network or putting data on the GPU. In your situation you can do everything without blocking.
Here is a decent page on this https://gamedev.stackexchange.com/questions/1589/fixed-time-step-vs-variable-time-step
There's a standard mechanism for this: Object.wait() and Object.notify() (with their overloads / variants). You simply wait for some event to occur in one thread, and some other thread is responsible for notifying you (or everyone, in case of notifyAll) of that occurrence.
You can also make use of the new Condition mechanism introduced in java.util.concurrent.
If you're making this in a game, why not try using something like Actions in libgdx? You just chain different actors together. Whenever a property like visibility or position reaches the value you want, you trigger the next action. Properties conditions are checked during each update loop of your game.
Or if its a swing app, use a timer to check these properties.
long t1=0,t2=0;
long nanoWaitTime=10000; //to wait at least 10000 nano-seconds
t1=System.nanoTime();
//start waiting
long count=0;
boolean releaseCpuResources=true;
while(Math.abs(t2-t1)<nanoWaitTime)
{
t2=System.nanoTime(); //needs maybe 1000 cycles of cpu to get this value.
//so this is like busy-wait
//and minimum step may be 1 micro-seconds or more
if(releaseCpuResources)
{
count++;
if(count>1000)Thread.sleep(1);//after too many iterations, cpu gets overwhelmed
//so Thread.sleep makes it better for large waiting
//times
//but precision is lost. Like uncertainity principle
//but in a quantized fashion
}
}
// here continue to work after waiting
The resolution or precision may not be what you want in for all cpus.

Is there some way to stop thread immediately?

I was wondering if there is some way in Java to stop thread immediately. I don't want to check its interrupted status, I need to stop it immediately. That's because in thread's run method there are many calculations and to achieve what I want using interrupted I would have to inject status check everywhere. So is there some way to interrupt thread immediately? Maybe stop() method? I know it's is said it shouldn't be used because of deadlocks but if it could solve my problem (even if it would cause another ;) ) I could use it. So? P.S. I know there were other, similar questions but everywhere people give similar questions to interrupted() which doesn't suit me.
The question/answer that #Alya'aGamal points to is the right one.
If your app's design assumes that forcibly stopping a thread, or a process, or a program (like using kill -9 or stopping it via the Task Manager on Windows) is an okay thing to do, then you really need to justify that, because it sounds like a bad design choice. If you used someone else's app and the only way to close it on demand was to forcibly stop it, wouldn't you think that was a rather major flaw?
If you have long-running loops or algorithms and it's important to be able to stop them at an arbitrary point then you MUST put some kind of regular status or signal check in place in order to do this properly.
Always design your apps in a way such that there is a nice, friendly, graceful way for them to exit from all situations other than things outside your control (e.g. another app starts saturating the CPU, a hard disk dies, a RAM chip gets fried, a meteor hits the Earth, etc.)
As others have said, it's not a good idea to just kill a thread, which is why the stop() method has been deprecated. It's just too easy to introduce deadlocks this way. There are other reasons why stopping a thread externally is bad, but I won't get into them here.
Status checks really are the only other way to go, but I can understand why you'd want to avoid them. Checks add overhead and make the code cumbersome if your run() method has many lines of code... but there's simply no other thread-safe way to stop a thread.
That said - there are four components of deadlock: mutual exclusion, hold and wait, non-pre-emption, and circular wait. If you can guarantee that any one of these conditions will never be met inside your run() method, then you will never encounter a deadlock by calling stop().

Which one is better for performance to check another threads boolean in java

while(!anotherThread.isDone());
or
while(!anotherThread.isDone())
Thread.sleep(5);
If you really need to wait for a thread to complete, use
anotherThread.join()
(You may want to consider specifying a timeout in the join call.)
You definitely shouldn't tight-loop like your first snippet does... and sleeping for 5ms is barely better.
If you can't use join (e.g. you're waiting for a task to complete rather than a whole thread) you should look at the java.util.concurrent package - chances are there's something which will meet your needs.
IMHO, avoid using such logic altogether. Instead, perhaps implement some sort of notification system using property change listeners.
As others have said, it's better to just use join in this case. However, I'd like to generalize your question and ask the following:
In general when a thread is waiting for an event that depends on another thread to occur is it better to:
Use a blocking mechanism (i.e. join, conditional variable, etc.) or
Busy spin without sleep or
Busy spin with sleep?
Now let's see what are the implications for each case:
In this case, using a blocking call will effectively take your thread off the CPU and not schedule it again until the expected event occurs. Good for resource utilization (the thread would waste CPU cycles otherwise), but not very efficient if the event may occur very frequently and at small intervals (i.e. a context switch is much more time-consuming than the time it takes for the event to occur). Generally good when the event will occur eventually, but you don't know how soon.
In case two, you are busy spinning, meaning that you are actively using the CPU without performing useful work. This is the opposite of case 1: it is useful when the event is expected to occur very very soon, but otherwise may occupy the CPU unnecessarily.
This case is a sort of trade-off. You are busy spinning, but at the same time allowing other threads to run by giving up the CPU. This is generally employed when you don't want to saturate the CPU, but the event is expected to occur soon and you want to be sure that you will still be there in almost real time to catch it when it occurs.
I would recommend utilizing the wait/notify mechanism that is built into all Java objects (or using the new Lock code in Java 5).
Thread 1 (waiting for Thread2)
while(!thread2.isDone()) {
synchronize(thread2.lockObject) {
thread2.lockObject.wait();
}
}
Thread 2
// finish work, set isDone=true, notify T1
thread2.lockObject.notify();
'lockObject' is just a plain (Object lockObject = new Object()) -- all Java objects support the wait/notify calls.
After that last call to notify(), Thread1 will wake up, hit the top of the while, see that T2 is now done, and continue execution.
You should account for interrupt exceptions and the like, but using wait/notify is hugely helpful for scenarios like this.
If you use your existing code, with or without sleep, you are burning a huge number of cycles doing nothing... and that's never good.
ADDENDUM
I see a lot of comments saying to use join - if the executing thread you are waiting on will complete, then yes, use join. If you have two parallel threads that run at all times (e.g. a producer thread and a consumer) and they don't "complete", they just run in lock-step with each other, then you can use the wait/notify paradigm I provided above.
The second one.
Better though is to use the join() method of a thread to block the current thread until it is complete :).
EDIT:
I just realised that this only addresses the question as it applies to the two examples you gave, not the question in general (how to wait for a boolean value to be changed by another Thread, not necessarily for the other Thread to actually finish).
To answer the question in general I would suggest that rather than using the methods you described, to do something like this I would recommend using the guarding block pattern as described here. This way, the waiting thread doesn't have to keep checking the condition itself and can just wait to be notified of the change. Hope this helps!
Have you considered: anotherThread.join() ? That will cause the current one to be 'parked' without any overhead until the other one terminates.
The second is better than the first, but neither is very good. You should use anotherThread.join() (or anotherThread.join(timeout)).
Neither, use join() instead:
anotherThread.join();
// anotherThread has finished executing.

Categories