Domanda

I'm using time elapsed as a variable in a program which I am currently debugging. As I am debugging this the time elapsed variable still increases whilst I am examining variables giving undesired results and makes debugging ineffective. Is there anyway to freeze time or stop the variable from changing? (I am using System.currentTimeMillis() to calculate the time).

Edit: I have an object in a space that moves as time increases, because I am using System.currentTimeMillis() to calculate how much time has passed, it doesn't work in debugging. I'd like to know if there is a way I can work around this, thanks.

È stato utile?

Soluzione

One common approach to this kind of problem is to use Dependency Injection. Create a class Clock (for example) which is initialized (injected) with a time source. In production code this source might well be System.nanotime() or System.currentTimeMillis(). In debugging you use a controllable clock. The debugging implementation of the Clock class has additional methods (e.g. suspend(), resume(), setClockTo()) that allow one to use simulated time.

Altri suggerimenti

System.currentTimeMillis() does what it is supposed to do: Give you the time at the moment the instruction is executed. When you are "examining variables" your program thread is suspended but time still is moving on... Thus the time increase

Your alternative is to not use to System.currentTimeMillis(). This is rather complicated because when you are debugging you want to time to step forward when the code is running.

The best solution is to change this requirement, so that this is not a problem.

e.g. say you have a timeout which is short, you can have it increase the timeout when you are running in the debugger.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top