I was working on my game loop and I came across an odd problem. The loop was working fine, my states could render, received updates, etc. I then proceeded to create my Input system, which, also works. However, after implementing that I continually & randomly receive a Exception in my thread stating: Exception in thread "Thread-3" java.lang.IllegalArgumentException: timeout value is negative
I first tried to debug this. The problem is there is 0 consistency with the exception occurring. KeyEvents seem to have no affect, due to the fact I can use the poll system & not generate an exception. That & sometimes upon running it automatically throws an exception. I've re-looked through the code and I'm not quite sure what is causing this.
For convenience I'll just leave the relevant code.
public class Game implements Runnable {
public int FPS = 0;
private Double delta;
private long lastFps = 0;
private final int TARGET = 60;
private final long OPTIMAL_TIME = 1000000000 / TARGET;
private boolean gameRunning = false;
@Override
public void run() {
long lastLoop = System.nanoTime();
while (gameRunning){
//Figure out how long its been since last update - used for entity calculation
long current = System.nanoTime();
long updateTime = current - lastLoop;
lastLoop = current;
delta = updateTime / ((double)OPTIMAL_TIME);
lastFps += updateTime;
FPS++;
if(lastFps >= 1000000000){
System.out.println("(FPS: "+ FPS +")");
lastFps = 0;
FPS = 0;
}
//Updates state + calls render
updateState();
/*
* We need each frame to take 10mill-sec
* Take recorded time + 10 milli
* then factor current time
* this ^ is final value to wait
*/
try{
Thread.sleep( (lastLoop - System.nanoTime() + OPTIMAL_TIME) /1000000 );
}
catch(InterruptedException exception){
exception.printStackTrace();
}
}
}
Unless the KeyEvent's could possibly have relation to the problem or my input polling (Which doesn't manage time or anything affecting the thread) I'm not sure if it's needed to post any relevant code from that class. (If you think I need to you're welcome to ask but it's just boolean arrays + a string cache).
The question: Why is the thread encountering a negative timeout value?