My program is a Java game which involves taking turns between the user and AI. Therefore after all operations are complete I have a infinite while loop which only breaks after the turn has changed. I only use an infinite loop because I am using a timer and cannot predict when the user ends their turn. But I notice that my program slows down over time to a point where even clicking buttons has no effect. Is it my loop which is causing this? Help would be appreciated.
while(true) {
if(playerTurn % 2 == 1) {
artificialIntelligence();
break;
}
}
If you use an infinite loop(while loop in your case) this operation would be performed continuously; thus slowing your application. Hence, I would suggest breaking the code into two threads.
First thread - Check user-turn event.
Second thread - Do the AI stuff.
As soon as the user event occurs, stop the thread and do what's needed.
This way your code would never be blocked at any point of time; thus resulting in better performance.
Without more code, it is hard to determine what is the real cause of the problem. However, one suspect may be that you're holding on to object references and they're not being reclaimed by garbage collection. Try using a java profiler, it can help you to pin point where exactly the issue may arise.
Related
i'm doing a task using other jframe. At now, i have 2 jframes, at jframe1 when i click button add new. Next, jframe2 will display and i want to catch event from this jframe when click, so i use thread and while(true) but it not working as i expected, after i click add at jframe2, thread at jframe1 not catch and it still loop infinite. i debuged, it's work ok but when i run it's not work as when i debug. what wrong there? Here my code in jframe1:
JButton btnNewButton = new JButton("add new");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Thread t = new Thread() {
public void run() {
System.out.println("start");
Frame2 f2 = new Frame2();
do {
if (f2.getCheck() == 0) {
System.out.println("catched");
break;
}
} while (true);
System.out.println("end");
};
};
t.start();
}
});
and here my code in jframe2:
JButton btnNewButton = new JButton("add");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
check = 0;
frame.dispose();
}
});
The Java Memory Model is to blame.
The JVM has an evil coin.
It will flip this coin sometimes. Specifically, anytime you access any field, the JVM flips the evil coin.
Heads, and the JVM will give you the value contained in this field that it has cached from earlier. The value that it had in this thread, regardless of any updates written to it from other threads.
Tails, and it will give you the value as it was written to last, by any thread.
It's evil, in the sense that it is not a fair coin: Today, and during your unit tests, and as the debugger runs, and with this particular phase of the moon, it works every time. Same tomorrow and next week. But 2 weeks from now just as you are giving that demo to the important customer? Reliably failing.
The key point is: If you make the JVM ever flip the coin, you lost.
Do not make the JVM flip it.
To disble the JVM's evil coin, you must establish so-called happens-before/happens-after relationships.
An HB/HA relationship works as follows:
For any 2 statements anywhere in your entire code base, the 2 statements either have HB/HA, or they do not.
If they do have HB/HA, then the JVM guarantees you that the happens-after line cannot observe any state as it was before the happens-before line, other than timing. In other words, code executes as if the statement that has the 'happens before' relationship with the 'happens after' line actually happened before. It doesn't actually have to, but you cannot observe that it didn't, so that doesn't matter.
However, if they do not have HB/HA, anything can happen. You may observe it, or not, even if you have absolute proof that line B ran after line A, then line B may or may not observe anything A changed, JVM's discretion: Evil coin flips occur.
You may find this all incredibly stupid design and obviously bizarre; why would the JVM have an evil coin and why is it playing these games?
The answer is efficiency. Inter-core communication is incredibly expensive. The JVM will often but not always attempt to run code efficiently and this usually involves a local cached copy. The JVM doesn't spend every moment checking if it has nothing to do and aggressively synchronizing all these caches together in some sensible fashion, that would be far too inefficient. CPUs have other stuff to do, and even if they don't, hey, laptops are a thing, as is the power bill, as is your Datacenter's provisioned CPU cycle counts, so spending CPU cycles that aren't neccessary is a waste that shouldn't be occurring.
So the JVM doesn't. It will happily leave things unsynced, or not, at is discretion, for days if it wants.
That is what you are observing. With the debugger fired up, all sorts of efficiencies aren't run because they would confuse the debugger, so you are observing from thread A that check = 0 many seconds after thread B set it to that value. But, without the debugger on, you may print something that tells you B has set check to 0, but then A sees that check isn't 0 for days on end.
In other words, in thread B, check seems to be 0. You can print the time and confirm that this happens at point in time X. And yet, even though it is clearly much, much later, A is still observing that check is still 3 or whatever it was before A set it to 0. The explanation is that B and A each have their own copy of check. The JVM isn't gonna sync em just cuz you want it to. And there is no simple syncItUp() method. And, yeah, there is no guarantee that these local copies are there either. The JVM is free to sync them up or not. With the debugger on, it syncs em. Without it, it doesn't. Weird, but the spec of the JVM gives the JVM the power to do it. Evil coin. The one, and only, way to guarantee things, is to establish HB/HA.
To establish HB/HA, well, you can search the web. But, the easy ways are:
The synchronized keyword: If thread A exits a block that synchronized on object ref to object X, that is guaranteed to 'happen before' any other thread that enters such a synchronized block later on.
Thread starts. If thread A starts thread B, then the line right before b.start(); is HB relative to the first line in thread B.
volatile. writes to volatile fields establish HB/HA vs. reads, though you get no guarantees if it actually runs earlier (these aren't locks). It would 'work' here in your case, though.
Any java library tool that internally uses this stuff. For example, just about everything in the java.util.concurrent package.
So, in short, make that volatile. More generally though, trying to read and write to the same field from different threads is Here Be Dragons and They WILL bite your head off! territory. It's hard to write the code properly and if you mess up, a unit test won't catch it. You'll have a flakey app that works great for you and fails on other machines or in bizarre conditions.
If you can, use proper tools (j.u.c classes are a good start), and try to just not write to fields from multiple threads, at all. For example, do all inter-thread comms via a database with proper transaction management.
I am studying multi-threading and now I am stuck. I read that Multi-threading in java is a process of executing multiple threads simultaneously. What does this 'simultaneously' mean? Also, multi-threading is based upon the concept of time-sharing, so how can the threads execute simultaneously? And if threads can't execute simultaneously, then how are we able to draw straight lines in paint by holding the shift key and dragging the mouse at the same time?
A short overview:
Indeed most Threads do not run at the same time. The trick is that threads switch often between one another. This gives the illusion of parallelism. (Similar to how images in quick succession give the illusion of continuous motion, quickly changing threads give the illusion of running at the same time)
How paint is implemented is anyone's guess. Here goes mine:
You press shift, a boolean flag gets raised
You move your mouse, the line is calculated
If you raise the shift key the bool flag is switched, causing the line not to be straight anymore
Ideed, key listening is an action that often is multithreaded. You have a thread that just asks all keys every few milliseconds if they were pressed. If so it sends a message to other treads (if they are listening for that particular key). The same goes for reading mouse movement.
Usually, you do not have to go in great detail for IO, as it is handled by most librarys/ frameworks for you. Also IO requires OS support, so that opens a new can of worms
I hope this helped
Processor can't execute several threads at one time, so threads are executing pseudo-simultaneously.
At this picture each color means each thread. Processor execute one thread then second etc. It seems like they are executing sumultaneously, but probably processor just change current thread and execute this.
What is both faster and "better practice", using a polling system or a event based timer?
I'm currently having a discussion with a more senior coworker regarding how to implement some mission critical logic. Here is the situation:
A message giving an execution time is received.
When that execution time is reached, some logic must be executed.
Now multiple messages can be received giving different execution times, and the logic must be executed each time.
I think that the best way to implement the logic would be to create a timer that would trigger the logic when the message at the time in the message, but my coworker believes that I would be better off polling a list of the messages to see if the execution time has been reached.
His argument is that the polling system is safer as it is less complicated and thus less likely to be screwed up by the programmer. My argument is that by implementing it my way, we reduce the reduce the computational load and thus are more likely execute the logic when we actually want it to execute. How should I implement it and why?
Requested Information
The only time my logic would ever be utilized would almost certainly be at a time of the highest load.
The requirements do not specify how reliable the connection will be but everyone I've talked to has stated that they have never heard of a message being dropped
The scheduling is based on an absolute system. So, the message will have a execution time specifying when an algorithm should be executed. Since there is time synchronization, I have been instructed to assume that the time will be uniform among all machines.
The algorithm that gets executed uses some inputs which initially are volatile but soon stabilize. By postponing the processing, I hope to use the most stable information available.
The java.util.Timer effectively does what your colleague suggests (truth be told, in the end, there really aren't that many ways to do this).
It maintains a collection of TimerTasks, and it waits for new activity on it, or until the time has come to execute the next task. It doesn't poll the collection, it "knows" that the next task will fire in N seconds, and waits until that happens or anything else (such as a TimerTask added or deleted). This is better overall than polling, since it spends most of its time sleeping.
So, in the end, you're both right -- you should use a Timer for this, because it basically does what your coworker wants to do.
We have JSF2.1 app deployed in weblogic10.3.4 ,in one of our backing bean ,when we try to assign the reference ArrayList to a List instance ,weblogic ends up in Struck thread ,during peak traffic to our application.
java.util.ArrayList.indexOf(ArrayList.java:210)
java.util.ArrayList.contains(ArrayList.java:199)
Any one has faced this issue before.
It is not entirely clear what you mean, so I'm going to assume that you mean a "stuck thread", and that the thread is stuck in the sense that it is continually executing at that point.
I can think of three plausible causes.
The object that is being searched for has a buggy equals(Object) method that in some circumstances goes into an infinite loop.
There are two (or more) threads accessing and/or updating the list roughly simultaneously, and you are not synchronizing properly. If you don't synchronize properly, there is a risk that the threads will see inconsistent views of the data structure, and that that will cause it behave in a way that seems impossible.
You've somehow set up a pathological situation that is causing one thread to be both reading and updating the list in the (incorrect) belief that it has two distinct lists.
My bet is that it is the second problem, since "heisenbugs" like that are more likely to occur when your server is under heavy load.
Finally, it is possible that the thread is not in an infinite loop, but is just taking a long time to do something. And it is possible that the loop involves other code, but each time you look at it is at that point.
This question already has answers here:
How can I abort a running JDBC transaction?
(4 answers)
Closed 5 years ago.
I have a program that continually polls the database for change in value of some field. It runs in the background and currently uses a while(true) and a sleep() method to set the interval. I am wondering if this is a good practice? And, what could be a more efficient way to implement this? The program is meant to run at all times.
Consequently, the only way to stop the program is by issuing a kill on the process ID. The program could be in the middle of a JDBC call. How could I go about terminating it more gracefully? I understand that the best option would be to devise some kind of exit strategy by using a flag that will be periodically checked by the thread. But, I am unable to think of a way/condition of changing the value of this flag. Any ideas?
I am wondering if this is a good practice?
No. It's not good. Sometimes, it's all you've got, but it's not good.
And, what could be a more efficient way to implement this?
How do things get into the database in the first place?
The best change is to fix programs that insert/update the database to make requests which go to the database and to your program. A JMS topic is good for this kind of thing.
The next best change is to add a trigger to the database to enqueue each insert/update event into a queue. The queue could feed a JMS topic (or queue) for processing by your program.
The fall-back plan is your polling loop.
Your polling loop, however, should not trivially do work. It should drop a message into a queue for some other JDBC process to work on. A termination request is another message that can be dropped into the JMS queue. When your program gets the termination message, it absolutely must be finished with the prior JDBC request and can stop gracefully.
Before doing any of this, look at ESB solutions. Sun's JCAPS or TIBCO already have this. An open source ESB like Mulesource or Jitterbit may already have this functionality already built and tested.
This is really too big an issue to answer completely in this format. Do yourself a favour and go buy Java Concurrency in Practice. There is no better resource for concurrency on the Java 5+ platform out there. There are whole chapters devoted to this subject.
On the subject of killing your process during a JDBC call, that should be fine. I believe there are issues with interrupting a JDBC call (in that you can't?) but that's a different issue.
As others have said, the fact that you have to poll is probably indicative of a deeper problem with the design of your system... but sometimes that's the way it goes, so...
If you'd like to handle "killing" the process a little more gracefully, you could install a shutdown hook which is called when you hit Ctrl+C:
volatile boolean stop = false;
Runtime.getRuntime().addShutdownHook(new Thread("shutdown thread") {
public void run() {
stop = true;
}
});
then periodically check the stop variable.
A more elegant solution is to wait on an event:
boolean stop = false;
final Object event = new Object();
Runtime.getRuntime().addShutdownHook(new Thread("shutdown thread") {
public void run() {
synchronized(event) {
stop = true;
event.notifyAll();
}
}
});
// ... and in your polling loop ...
synchronized(event) {
while(!stop) {
// ... do JDBC access ...
try {
// Wait 30 seconds, but break out as soon as the event is fired.
event.wait(30000);
}
catch(InterruptedException e) {
// Log a message and exit. Never ignore interrupted exception.
break;
}
}
}
Or something like that.
Note that a Timer (or similar) would be better in that you could at least reuse it and let it do with all of the details of sleeping, scheduling, exception handling, etc...
There are many reasons your app could die. Don't focus on just the one.
If it's even theoretically possible for your JDBC work to leave things in a half-correct state, then you have a bug you should fix. All of your DB work should be in a transaction. It should go or not go.
This is Java. Move your processing to a second thread. Now you can
Read from stdin in a loop. If someone types "QUIT", set the while flag to false and exit.
Create a AWT or Swing frame with a STOP button.
Pretend you are a Unix daemon and create a server socket. Wait for someone to open the socket and send "QUIT". (This has the added bonus that you can change the sleep to a select with timeout.)
There must be hundreds of variants on this.
Set up a signal handler for SIGTERM that sets a flag telling your loop to exit its next time through.
Regarding the question "The program could be in the middle of a JDBC call. How could I go about terminating it more gracefully?" - see How can I abort a running jdbc transaction?
Note that using a poll with sleep() is rarely the correct solution - implemented improperly, it can end up hogging CPU resources (the JVM thread-scheduler ends up spending inordinate amount of time sleeping and waking up the thread).
I‘ve created a Service class in my current company’s utility library for these kinds of problems:
public class Service implements Runnable {
private boolean shouldStop = false;
public synchronized stop() {
shouldStop = true;
notify();
}
private synchronized shouldStop() {
return shouldStop;
}
public void run() {
setUp();
while (!shouldStop()) {
doStuff();
sleep(60 * 1000);
}
}
private synchronized sleep(long delay) {
try {
wait(delay);
} catch (InterruptedException ie1) {
/* ignore. */
}
}
}
Of course this is far from complete but you should get the gist. This will enable you to simply call the stop() method when you want the program to stop and it will exit cleanly.
If that's your application and you can modify it, you can:
Make it read a file
Read for the value of a flag.
When you want to kill it, you just modify the file and the application will exit gracefully.
Not need to work it that harder that that.
You could make the field a compound value that includes (conceptually) a process-ID and a timestamp. [Better yet, use two or more fields.] Start a thread in the process that owns access to the field, and have it loop, sleeping and updating the timestamp. Then a polling process that is waiting to own access to the field can observe that the timestamp has not updated in some time T (which is much greater than the time of the updating loop's sleep interval) and assume that the previously-owning process has died.
But this is still prone to failure.
In other languages, I always try to use flock() calls to synchronize on a file. Not sure what the Java equivalent is. Get real concurrency if you at all possibly can.
I'm surprised nobody mentioned the interrupt mechanism implemented in Java. It's supposed to be a solution to the problem of stopping a thread. All other solutions have at least one flaw, that's why this mechanism is needed to be implemented in the Java concurrency library.
You can stop a thread by sending it an interrupt() message, but there are others ways that threads get interrupted. When this happens an InterruptedException is thrown. That's why you have to handle it when calling sleep() for example. That's where you can do cleanup and end gracefully, like closing the database connection.
Java9 has another "potential" answer to this: Thread.onSpinWait():
Indicates that the caller is momentarily unable to progress, until the occurrence of one or more actions on the part of other activities. By invoking this method within each iteration of a spin-wait loop construct, the calling thread indicates to the runtime that it is busy-waiting. The runtime may take action to improve the performance of invoking spin-wait loop constructions.
See JEP 285 for more details.
I think you should poll it with timertask instead.
My computer is running a while loop 1075566 times in 10 seconds.
Thats 107557 times in one second.
How often is it truly needed to poll it? A TimerTask runs at its fastest 1000 times in 1 second. You give it a parameter in int (miliseconds) as parameters. If you are content with that - that means you strain your cpu 108 times less with that task.
If you would be happy with polling once each second that is (108 * 1000). 108 000 times less straining. That also mean that you could check 108 000 values with the same cpu strain that you had with your one while loop - beause the you dont assign your cpu to check as often. Remember the cpu has a clock cycle. Mine is 3 600 000 000 hertz (cycles per second).
If your goal is to have it updated for a user - you can run a check each time the user logs in (or manually let him ask for an update) - that would practically not strain the cpu whatsoever.
You can also use thread.sleep(miliseconds); to lower the strain of your polling thread (as it wont be polling as often) you where doing.