Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to change the current time of a thread or jvm instance in java?

I want to test some class methods that contain logic dependent on the current time it is running. I'd like to set the thread/jvm/system time to a specific future date in the JUnit setup and run my tests. Also I would like this to be temporary. Has anyone done this before?

I was thinking of something similar to TimeZone.setDefault(timezone)

like image 957
Chip Avatar asked Aug 28 '10 20:08

Chip


People also ask

How do you make a thread wait for some time?

sleep() method. So the main thread can wait for some time and in the meantime, T1 will resume and complete its execution.

What thread keeps JVM running?

All Java programs have at least one thread, known as the main thread, which is created by the Java Virtual Machine (JVM) at the program's start, when the main() method is invoked.

When we start execution of Java application then JVM starts how many threads?

When a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program because it is the one that is executed when our program begins.

What is a thread in JVM?

What Is a Thread in Java? A Java thread is the execution path in a program. Everything that runs in Java is run in threads. Every application in the JVM world has threads, at least one, even if you don't call it explicitly. It all starts with the main method of your code, which is run in the main application thread.


3 Answers

You could use AspectJ and wrap methods around java.lang.System.currentTimeMillis(), java.util.Date.new() and java.util.Calendar.getInstance() which adjust the time according to your needs.

like image 129
tobiasbayer Avatar answered Nov 14 '22 23:11

tobiasbayer


I don't believe there's a way of doing this using java.util.Date.

If you are using joda-time then you can. See this

like image 29
Mike Q Avatar answered Nov 15 '22 01:11

Mike Q


I have been struggling with this too. The best solution I found so far is having a TimeHelper class which manages the time stuff : as a Date factory, keeping DateFormatters and so on so that these things are not distributed over the codebase.

With Easymock, or another mock framework, it is then straightforward to test time related stuff.

like image 28
Peter Tillemans Avatar answered Nov 14 '22 23:11

Peter Tillemans