Prevent Thread Subclass from waiting - java

I'm making a coding game for the Java class I TA. The game is to manage a fleet of trucks (Truck extends Thread) on an undirected graph to deliver parcels to their various destinations using as little time/fuel as possible. The student extends an abstract manager class that fills in the gaps in the Truck's behavior (what to do upon reaching a destination, etc). The truck class's run method is a event loop that waits for user instruction and then follows it when it receives travel destinations. Here's the event loop:
#Override
/** The Truck's main running routine. While the travel directions are empty,
* Waits for more instructions in WAIT_TIME intervals. While the travel directions
* are not empty, pops off the next travel direction
*/
public void run(){
while(game.isRunning()){
setGoingTo(null);
while(travel.isEmpty() && game.isRunning()){
try{
Thread.sleep(WAIT_TIME);
}
catch (InterruptedException e){
e.printStackTrace();
}
setStatus(Status.WAITING);
game.getScore().changeScore(Score.WAIT_COST);
}
while(!travel.isEmpty() && game.isRunning()){
Edge r = getTravel();
try {
travel(r);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
The first inner while loop loops while there are no travel instructions to follow. As you can see, every WAIT_TIME milliseconds (a frame), the score is decreased by the wait cost - the cost of the truck idling.
I realized, however, that a way for a potential solution to get around this cost is to tell the truck (thread) to wait while it doesn't have instructions, then notify it once the user has computed instructions for it. I'd like to prevent this programmatically, rather than just put in the instructions not to do it.
Is this even possible? Perhaps a method in the thread class to override? Can a class that extends Thread be prevented from waiting (on anything?) I'd settle for any kind of exception being thrown if a truck thread tries to execute .wait().
Thanks for reading and for any suggestions for how to tackle this gap in the rules! The game will be up on a public repo soon if you want to try your hand at it.

I don't have a solution for the exact question you asked (how to prevent wait), but a suggestion that is kind of too long for a comment:
How about measuring the time between the start of the first while loop and the end.
long starttime = System.currentTimeMillis();
setStatus(Status.WAITING);
while(travel.isEmpty() && game.isRunning()){
try{
Thread.sleep(WAIT_TIME);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
long endtime = System.currentTimeMillis();
long waittime = endtime - starttime;
game.getScore().changeScore(Score.WAIT_COST * (1 + waittime / WAIT_TIME));
Even if the thread is sent to sleep, the score will change according to the ellapsed time. You will just not have a live game score update.

I'm pretty sure you can't prevent .sleep() or .wait() because you can't override or tamper with them. So the only way is monitoring for them.
I don't know of a method inside the thread but from outside the thread (for example from a monitoring thread) you can get the thread staus with
Thread.getState()
if someone called sleep on the thread or the thread is waiting becuase of a wait call the result should be Thread.State.TIMED_WAITING. Then all you have to ensure is that the monitoriong thread knows it were the students that called sleep and not you (a private flag for example).
The monitoring thread can then of course take any counter measures you want like throwing an Exception or simply silently decucting points.
Relevant docs :
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.State.html#TIMED_WAITING
http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#getState()

I wonder whether having a Thread per Truck is the right approach. Are you trying to teach them about threads? or are you trying to teach them about graph algorithms and heuristics? (If the Single Responsibility Principle applies to homework assignments, then the answer should be one or the other, but not both.)
If the emphasis was on algorithms and heuristics, then I would write a single-threaded program where the main loop executes a series of "moves". In each move, it would ask each of the truck objects what the truck wants to do next, and then it would either move the truck accordingly, or it would flag the assignment as invalid if the truck asked to do something that did not make sense.
In my version, the "time" in the simulation would be completely decoupled from real-time, so if some student put a Thread.sleep() in her/his strategy routine, it would not have any effect on the outcome of the program; it only would make the program take that much longer to run. (Of course, I would run them all under control of a batch script that would abort any assignment that took longer than... say, three minutes.)

Related

Managing Java threads in a CPU instruction pipeline simulator

I have implemented a 5-Stage CPU instruction pipeline simulator in Java using multi-threading.
Each Stage is a thread that performs mainly below 3 functions, also there is a queue (of capacity 1) in-between every two stages.
Receive from the previous stage.
Process i.e. perform its main responsibility.
Forward to the next stage.
#Override
public void run() {
while (!(latchQueue.isEmpty())) {
fetch();
process();
forward();
}
}
Simulation works fine. This is where I’m stuck, I want to be able to simulate only a specified number of clock cycles. so, the simulator should stop/pause once it has reached the specified number of cycles.
As of now, I have started all the 5 threads and let it simulate the processing of all the instructions rather than limiting it by clock cycles.
How can I accomplish this? do I need to pause thread when specified clock cycles have reached? If so how can I gracefully handle suspending/stopping the threads? Please help me in choosing the best possible approach.
Thanks in advance :)
You are already using some concurrent queue to communicate between the threads (exactly how it works isn't clear because your code example is quite incomplete).
So you can count cycles at the first stage, and use that same mechanism to communicate: shove a sentinel object, which represents "time to stop/pause this thread", onto the queue for the first stage, and when processed it pauses the processor (and still forwards it to the next stage, so all stages will progressively shut down). For example, you could extend the type of objects passed in your queue so that the hierarchy contains both real payload objects (e.g., decoded instructions, etc) or "command objects" like this stop/pause sentinel.
Another asynchronous solution would be to Thread.interrupt each thread and add an interrupt check in your processing loop - that's mostly to gracefully shut down, and not so much to support a "pause" functionality.
Will following work?
Share following class CyclesCounter between all your threads representing stages. It has tryReserve method, getting true from it means thread has got enough "clock cycles" for its' next run. Getting false means there's not enough cycles left. Class is thread-safe.
After getting false, perhaps, your thread should just stop then (i.e., by returning from run()) -- no way it can get enough nr of cycles (due to your requirements, as I understood them), until whole session is run again.
class CyclesManager {
private final AtomicInteger cycles;
CyclesManager(int initialTotalCycles) {
if (initialTotalCycles < 0)
throw new IllegalArgumentException("Negative initial cycles: " + initialTotalCycles);
cycles = new AtomicInteger(initialTotalCycles);
}
/**
* Tries to reserve given nr of cycles from available total nr of cycles. Total nr is decreased accordingly.
* Method is thread-safe: total nr of is consistent if called from several threads concurrently.
*
* #param cyclesToReserve how many cycles we want
* #return {#code true} if cycles are ours, {#code false} if not -- there's not enough left
*/
boolean tryReserve(int cyclesToReserve) {
int currentCycles = cycles.get();
if (currentCycles < cyclesToReserve)
return false;
return cycles.compareAndSet(currentCycles, currentCycles - cyclesToReserve);
}
}

Java score points automatically increasing

I'm doing a school project. I am building a text based game on Java for PC.
The game I'm building is quite simple, you buy homes and you rent them out. So what I am asking is, how can i get the money to automatically increase per second ($1 per second) from each house and then automatically add it to their users bank account automatically. I have looked around and they say use a thread to pause the game for 1000(milliseconds) and then do counter++. But I have tried that, and for a text based game that pauses the game and makes the user wait. I want the user to continue interacting with other functionalities of the text based game whilst the money per second in his bank is increasing.
I agree that putting in a thread to sleep for 1000 ms is probably the best solution. The issue that you seem to have encountered when trying that solution is likely caused not using multithreading. The Thread.sleep(1000); command should be on a separate thread from the main thread that you are using for the user interface.
The following could be a possible way to implement the thread that modifies the bank balance:
public class RevenueThread implements Runnable {
public void run() {
while(true){
// add to bank balance
MainClass.BankBalance += MainClass.PropertyCount * INCOME_PER_PROPERTY;
// sleep for 1 second
try{
Thread.sleep(1000);
}catch(Exception ex){
System.err.println( ex.getMessage() );
}
}
}
}
Modify that code to your needs with the proper variable names and whatnot.
To integrate this with your code, you could add this to your main() function:
Runnable rev = new RevenueThread();
Thread revThread = new Thread(rev);
revThread.start();`
Note: I apologize if my answer seems somewhat brief or if it contains any errors. I am typing this solution from my phone, so bear with me :P
EDIT: The following is an alternative (and perhaps more accurate) way to increment the bank balance every second:
public class RevenueThread implements Runnable {
public void run() {
// Variable to keep track of payout timing:
long lNextPayout = System.currentTimeMillis() + 1000; // Current time + 1 second
while(true){
if(lNextPayout <= System.currentTimeMillis()){
// At least 1000 milliseconds have passed since the last payout
// Add money to the player's bank balance
MainClass.BankBalance += MainClass.PropertyCount * INCOME_PER_PROPERTY;
// Now set up the next payout time:
lNextPayout += 1000;
}
// sleep for 50 milliseconds to prevent CPU exhaustion
try{
// Thread.sleep() can throw an InterruptedException.
Thread.sleep(50);
}catch(Exception ex){
// If sleep() is interrupted, we should catch the exception
// and print the error message to the standard error stream
// (STDERR) by using System.err
System.err.println( ex.getMessage() );
}
}
}
}
What's different about this version and why is it better? This version uses the system's current time to payout every 1000 milliseconds. Because sleep() can possibly throw an exception, this updated version prevents a user from being paid multiple times within 1 second just because sleep() threw an exception and did not sleep for the full second.
How can this be used? This can be used in the exact same way as the previous version. (I.e., just create a new RevenueThread object, then create a Thread object for it, and call .start() on that new thread.) Again, though, you should replace and rename variables as needed to fit into your project.
Since you are doing a text based game and it is not indicated in your question whether this will be a multiplayer or single player game, if this is a single player game, I will not implement this simulation (game) in real time.
It is probably more suitable to implement a discrete-time simulation (which means you don't have to use threads). You can create each house as an object with a currentTime attribute. Every time a house is rented, update its currentTime. Whenever you need to check the bank account for the money received from renting. Check the elapsed renting time of each house and update your bank account accordingly.

UI updates as expected in debug mode, but does nothing when run normally

I'm creating a simple game turn based game in NetBeans. After the initialization of the GUI it calls the function herosTurn() to which waits for the users choice and and creates the outcome of that choice from a separate class Hero. When I step through the code in Debug mode, I get correct outcomes, but if I just run the code nothing is ever appended to the Text Area unless I have the wait function constantly appending text while it waits for input. I've seen other questions similar to this but they all involved multi-threading, and I don't believe that is what I am doing. Any help would be greatly appreciated.
This is the main class:
package Flow;
import Forms.Battleinterface;
/**
*
* #author Steemo
*/
public class battle {
public static int hAct;
public static int gLife = 200;
public static void herosTurn() {
hAct = 0;
Forms.Battleinterface.biText.append("What will you do?");
while (hAct == 0){
// adding the line below makes code work but is ugly.
//Forms.Battleinterface.biText.append(".");
continue;
}
if (hAct == 1){
Entities.Hero.attack();
}
}
public static void main(String args[]) {
Battleinterface battleinterface = new Forms.Battleinterface();
Battleinterface.Start();
while (gLife > 0) {
herosTurn();
}
}
}
And this is the Hero() class that is in a separate package:
package Entities;
import java.util.Random;
/**
*
* #author Steemo
*/
public class Hero {
static Random hGen = new Random(54154454);
public static void attack() {
int hAtt = 0;
hAtt = hGen.nextInt(6) + 15;
Forms.Battleinterface.biText.append("\nYou swing your axe and do " + hAtt
+ " Damage!!!");
}
}
I am not attaching the class I use to generate the GUI (Battleinterface) because the GUI generates fine and the only other thing happening there is the passing of the input hAct.
If it is needed I can attach it.
Replace this code...
while (hAct == 0){
continue;
}
...with this instead:
while (hAct == 0){
try {
Thread.yield();
} catch (InterruptedException interruptedEx) {
// Log the interruption somewhere.
}
}
Assuming you're using AWT/Swing on some level? This is an infinite loop, preventing other threads from ever running. By doing this you never let the UI thread actually do any updating, which means it appears to hang. You may not be doing any threading on your own, but AWT/Swing comes with Threads built in to do various functions, and they need to periodically get CPU time to do their work.
The reason this works in debugging is because the debugger is pausing the herosTurn method as you're stepping through it, allowing the UI thread to do its updates (including getting input from the user), but when simply running your game, the herosTurn method never pauses, and that method is occupying 100% of the available CPU time for your app.
Finally, as Mike Clark mentions, you typically shouldn't write UI with infinite loops. Instead you define components, which trigger events. Your code is notified of those events and reacts appropriately. This is what is known as the UI's event model. If you're using Swing, the introductory info on working within the event model is covered here.
I also wouldn't typically use AWT/Swing for games, because of the complications of UI coding, rendering performance, and several other reasons relating to the reality that AWT/Swing were not built to be good tools for games. That being said, a turn-based game can work fine this way (because the rendering performance requirements are often much lower) if you're willing to delve into the UI code to get it done, in addition to a few other reasons which I've outlined in a previous answer.
Hmm, there might be an issue with flushing your text buffer to the text area. Try explicitly flushing your text buffer after every print to see if that makes a difference.
It seems to me that your program is stuck in a while loop in the method herosTurn() As long as that function has not returned, nothing is going to update if you program this game as a single thread application.
It works when you uncomment the Forms.Battleinterface.biText.append("."); line cos then you send a signal to the GUI every iteration which causes it to update.
Games usually have a main game loop from which all elements of the program are controlled. Maybe a change of your implementation strategy will help?
I'm not a games programmer, so this might not be the best approach, but why don't you try setting up a javax.swing.Timer that runs every, say, 100 milliseconds. In inside the timer action, you can write all the code which checks and advances the game state and generates output to the user.
I'd suggest collecting the user's input in a JTextField that is separate from the place where the game output is printed. If you want to know when the user presses enter to send what they've typed, you can register an ActionListener on the JTextField.
textField.addActionListener(yourListener);

why my android project raise CPU usage range from 60% ~ 100%?

Hello I'm making a chat application in android
so overall, I have a service which contains lots of classes and threads.
in my service, i had socket input read class, socket output writer class, and pinger that in summary have 6 threads.
Actually, i'm very new with this problem, well i can say i have no idea what makes a program occupy high percentage of CPU processes. is it cause too many static variables maybe? or too many running threads maybe, or too many local variables maybe?
I don't know exactly what is going on...?
So, please share with me your experiences and knowledge
UPDATE
public void run() {
while(isRunning) {
try {
Thread.sleep(500);
if(!startCheck) {
//Log.v(TAG, "SocketQueue: "+socketTaskQueue.size()
if(socketTaskQueue.size() > 0) {
processSocketTask();// TODO
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
so basically, i made my threads like above example.
so, i have a vector called socketTaskQueue, and this thread job's is to check whether there's a socket task or not. if it does, then it will execute processSocketTask function that will get the top element of the vector queue and then remove it.
UPDATE
T.T this post is embarrassing! i forget to put Thread.sleep() in some of my threads!
SORRY FOR BOTHERING YOU GUYS! :p
It is caused, usually, by threads that use CPU even when they cannot accomplish useful work. For example, when a thread is waiting for something to happen, does it wait in a way that uses no CPU? Or does it keep waking up needlessly even before it can do work?
It can also be caused by threads that do work in extremely inefficient ways.

Thread.sleep() in a while loop

I notice that NetBeans is warning me about using Thread.sleep() in a while loop in my Java code, so I've done some research on the subject. It seems primarily the issue is one of performance, where your while condition may become true while the counter is still sleeping, thus wasting wall-clock time as you wait for the next iteration. This all makes perfect sense.
My application has a need to contact a remote system and periodically poll for the state of an operation, waiting until the operation is complete before sending the next request. At the moment the code logically does this:
String state = get state via RPC call
while (!state.equals("complete")) {
Thread.sleep(10000); // Wait 10 seconds
state = {update state via RPC call}
}
Given that the circumstance is checking a remote operation (which is a somewhat expensive process, in that it runs for several seconds), is this a valid use of Thread.sleep() in a while loop? Is there a better way to structure this logic? I've seen some examples where I could use a Timer class, but I fail to see the benefit, as it still seems to boil down to the same straightforward logic above, but with a lot more complexity thrown in.
Bear in mind that the remote system in this case is neither under my direct control, nor is it written in Java, so changing that end to be more "cooperative" in this scenario is not an option. My only option for updating my application's value for state is to create and send an XML message, receive a response, parse it, and then extract the piece of information I need.
Any suggestions or comments would be most welcome.
Unless your remote system can issue an event or otherwise notify you asynchronously, I don't think the above is at all unreasonable. You need to balance your sleep() time vs. the time/load that the RPC call makes, but I think that's the only issue and the above doesn't seem of concern at all.
Without being able to change the remote end to provide a "push" notification that it is done with its long-running process, that's about as well as you're going to be able to do. As long as the Thread.sleep time is long compared to the cost of polling, you should be OK.
You should (almost) never use sleep since its very inefficient and its not a good practice. Always use locks and condition variables where threads signal each other. See Mike Dahlin's Coding Standards for Programming with threads
A template is:
public class Foo{
private Lock lock;
private Condition c1;
private Condition c2;
public Foo()
{
lock = new SimpleLock();
c1 = lock.newCondition();
c2 = lock.newCondition();
...
}
public void doIt()
{
try{
lock.lock();
...
while(...){
c1.awaitUninterruptibly();
}
...
c2.signal();
}
finally{
lock.unlock();
}
}
}

Categories

Resources