Im creating a “Fake-time” or TimeSource for my application, the point is that this new class should control the application’s actual time. This means all the methods that uses Date() constructor, System.currentTimeInMillis(), or Calendar.getInstance(), should instead use my class (ex. TimeSource.getInstance.getCurrentTimeInMillis()).
This way i can manipulate the system’s actual time when in a testing environment.
But i wonder if i should synchronize these methods, or how i should to it.
I can show you the following code:
public class DateTime {
private static final long ONE_MINUTE = 60 * 1000;
private static final long ONE_HOUR = ONE_MINUTE * 60;
private static final long ONE_DAY = ONE_HOUR * 24;
private static final long ONE_MONTH = ONE_DAY * 30;
private static final long ONE_YEAR = ONE_DAY * 364;
private static DateTime instance;
private Date date;
private Date staticDate;
private boolean isStatic = false;
private long addedTimeInMilliseconds = 0;
public static DateTime getInstance() {
if (instance == null) {
instance = new DateTime();
}
return instance;
}
private DateTime() {
date = new Date(System.currentTimeMillis());
staticDate = new Date(System.currentTimeMillis());
}
public Date getCurrentTime() {
if (isStatic) {
return staticDate;
} else {
date.setTime(System.currentTimeMillis()+this.addedTimeInMilliseconds);
return date;
}
}
public long getCurrentTimeInMillis() {
if (isStatic) {
return staticDate.getTime();
} else {
return System.currentTimeMillis()+this.addedTimeInMilliseconds;
}
}
}
Ive run some tests on the methods – both single and multithread tests – and the performance with syncronized methods is alot worse than without the synchronized. Problem is that im unsure if the methods might make problems in the future if i do not synchronize them.
I also use a few methods to add to the “current application’s time”
public void addMinutesToDateTime(int minutes) {
this.addedTimeInMilliseconds += (minutes * ONE_MINUTE);
}
So im asking a little advice, or knowledge about synchronized, and weather or not i should use it on my methods.
Best regards – Martin.
I would have only one thread updating the time and make the fields
volatileif needed.I wouldn’t use
Datein a mutable way, I would uselong.