Speeding up Java clock (override how Date class/System.getCurrentTimeInMillis works) - java

We have an existing product that is very time sensitive. For example, statistics are published on a 5 min, 1 hour, 24 hour basis. This means testing is very slow in real world conditions (we actually don't test the 1 hour and 24 hour statistics because of this).
What I want is to speed up the JVM clock.... I know I could create a dummy time class as I've seen others do. But the code base is huge so this would be a lot of retrofit work + third party libs would still use the normal Date Class/System.getCurrentTimeInMillis...
What I'm really looking for is a way to override the Java time behavior (monkey patching in the ruby world). I'm guessing it should be possible to use byte code manipulation to do this. But I'm not sure where to start.... I can't find any libraries that do this or anyone who has solved this problem via byte code manipulation.
question 1: is it possible to override the Date behavior?
question 2: how would one do this? Perhaps an example of overriding another core java class?
thanks for any thoughts

Modify the system time (disable ntpd if in use), Java time will reflect accordingly.

There are two main approaches. Modify the Date class itself, or modify all references to it.
The Date class is part of the standard library, so it's given a privileged status. The only way I can think of to modify it is to actually modify the system jar. You can either put your modified jar in the normal location or tell the JVM to look elsewhere. Note that this is not officially supported by Oracle and is only really feasible for personal use.
The other approach is to modify all your classes to reference a mocked version of the class. Even in a large codebase, you can do this with a simple script. If you only care about normal references you can do this either statically or dynamically (as classes are loaded).
If you're worried about accessing Date via reflection, doing it dynamically is the only option. Typically you would use a custom class loader with ASM to do bytecode rewriting. In order to capture reflection, you would have to mock out all the reflection classes and replace references to those too. This gets pretty tricky, especially when you consider the possibility of using reflection to access reflection to access Date, but it's possible.
Also, note that bytecode rewriting won't let you mess with the system classes because they use the hardcoded system classloader. So if another system class references Date, it will use the unmodified version.
I believe Java Agents can also be used to do bytecode rewriting without the need for a custom classloader, but I don't have experience with this.

Java 8
Java 8 includes a new java.time.* package, defined by JSR 310, inspired by Joda-Time (but re-architected).
These new classes supplant the notoriously troublesome classes of java.util.Date, java.util.Calendar, and java.text.SimpleDateFormat.
Mock Clock
Amongst the new classes is the abstract class, Clock.
The designers had exactly your need in mind, a pluggable replacement for the system clock to create fake "mock" date-time values to facilitate testing. The Clock class is meant to be extended by you (or others) for whatever unnatural behavior you desire. Pass an instance of that altered clock to the other java.time.* classes. Those other classes will use your Clock as a source of date-time data rather than the computer/JVM's real clock.
Joda-Time
Looks like Joda-Time may have something similar. Read this discussion about a "MillisProvider". Apparently referring to DateTimeUtils.MillisProvider.

Related

Why it is bad, that java.util.date is mutable? [duplicate]

As most people are painfully aware of by now, the Java API for handling calendar dates (specifically the classes java.util.Date and java.util.Calendar) are a terrible mess.
Off the top of my head:
Date is mutable
Date represents a timestamp, not a date
no easy way to convert between date components (day, month, year...) and Date
Calendar is clunky to use, and tries to combine different calendar systems into one class
This post sums it up quite well, and JSR-310 also expains these problems.
Now my question is:
How did these classes make it into the Java SDK? Most of these problems seem fairly obvious (especially Date being mutable) and should have been easy to avoid. So how did it happen? Time pressure? Or are the problems obvious in retrospect only?
I realize this is not strictly a programming question, but I'd find it interesting to understand how API design could go so wrong. After all, mistakes are always a good learning opportunity (and I'm curious).
Someone put it better than I could ever say it:
Class Date represents a specific instant in time, with millisecond
precision. The design of this class is a very bad joke - a sobering
example of how even good programmers screw up. Most of the methods in
Date are now deprecated, replaced by methods in the classes below.
Class Calendar is an abstract class for converting between a Date
object and a set of integer fields such as year, month, day, and hour.
Class GregorianCalendar is the only subclass of Calendar in the JDK.
It does the Date-to-fields conversions for the calendar system in
common use. Sun licensed this overengineered junk from Taligent - a
sobering example of how average programmers screw up.
from Java Programmers FAQ, version from 07.X.1998, by Peter van der Linden - this part was removed from later versions though.
As for mutability, a lot of the early JDK classes suffer from it (Point, Rectangle, Dimension, ...). Misdirected optimizations, I've heard some say.
The idea is that you want to be able to reuse objects (o.getPosition().x += 5) rather than creating copies (o.setPosition(o.getPosition().add(5, 0))) as you have to do with immutables. This may even have been a good idea with the early VMs, while it's most likely isn't with modern VMs.
Java's early APIs are nothing more than a product of their time. Immutability only became a popular concept years after that. You say that immutability is "obvious". That might be true now but it wasn't then. Just like dependency injection is now "obvious" but it wasn't 10 years ago.
It was also at one time expensive to create Calendar objects.
They remain that way for backwards compatibility reasons. What is perhaps more unfortunate was that once the mistake was realized the old class wasn't deprecated and new date/time classes were created for all APIs going forward. This has to some degree occurred with the JDK 8 adoption of a JodaTime like API (java.time, JSR 310) but really it's too little too late.
Time is itself not easy to measure and to handle with. Just look at the length of the wikipedia article about time. And then, there are different understandings about time itself: a absoulte time point (as a constant), a time point at a certain place, a time range, the resolution of time....
I remember, when i saw java.util.Date the first time (JDK 1.0?) i was really happy about it. The languages i knew of didn't had such a feature. I didn't have think about time conversion etc.
I think it's mess, because everything that changes leaves a mess if you evolve from one level of understanding (XMLGregorianCaldender vs. Date) and requirements (Nanoseconds, past 2030) to higher level, but keeping the old untouched. And java.util.Date is not a Exception. Just look at the I/O subsystem or the transition from AWT to Swing...
And because of that, "we should sometimes press the reset button." (who said that, btw.?)

Term to distinguish "default" vs "made-up" classes in OOP

arraylists, buffered reader, scanner, etc.. all "Default" classes that "already exist" in the language..
unlike, say, public class widthOfTable which would be a "made up" class , that " did not already exist in language"..
why is there no term to distinguish these ideas when teaching? I barely discovered this difference in college , despite being here 3 years.
Actually, there is a pretty strong distinction between what you called "default" and "made-up" classes, which has to do with their package names.
All "default" classes are in some java.* package (java.lang, java.util, etc.), and no "made up" class could use a package name that starts with java..
As for the fact that this distinction is blurred "when teaching", my feeling is that it's intentional. Java as a language is pretty much a set of keywords and syntax rules plus a java.lang.Object class that nobody could avoid extending (and which uses a few other built-in types like String, Integer and some exceptions).
The JDK is a Java library to help you with the most common use-cases, but in some cases there are better alternatives.
In my opinion, it would be a mistake to teach someone that java.util.Calendar or the java.util.logging stuff have any advantage over JodaTime or SLF4J just because they're in the classpath by default.
I had the same question in my mind before and i had a different term for your word default and I called them built-in classes.
why is there no term to distinguish these ideas when teaching?
there is already but taught indirectly using the terms packages and namespaces
if there is a time that you will design a programminng language you can tell any developer what are those default or built classes by putting them in right packages and namespaces for example
mydefaultclasses.io.print
mydefaultclasses.io.read
in java its really understandable that any classes under java namespace is a default or built-in class. it really depends upon what will came up on the documentation of the language you are trying to learn.
Not sue if I totally understand your question, but you can find all the predefined classes in Java under the Java Class Library: Java Class Library.
Actually it is more powerful to have packages or namespaces. Your way of thinking is like an implementation that only supports two namespaces. The standard library (in this case the java.*, in c++ std) is one, the other is all your other stuff. After a while, you probably end up with a new set of "default" classes anyway and you put those in a package to avoid clutter your global namespace.

Why do so many of the Java libraries take `String` where `CharSequence` would do?

I was frustrated recently in this question where OP wanted to change the format of the output depending on a feature of the number being formatted.
The natural mechanism would be to construct the format dynamically but because PrintStream.format takes a String instead of a CharSequence the construction must end in the construction of a String.
It would have been so much more natural and efficient to build a class that implemented CharSequence that provided the dynamic format on the fly without having to create yet another String.
This seems to be a common theme in the Java libraries where the default seems to be to require a String even though immutability is not a requirement. I am aware that keys in Maps and Sets should generally be immutable for obvious reasons but as far as I can see String is used far too often where a CharSequence would suffice.
There are a few reasons.
In a lot of cases, immutability is a functional requirement. For example, you've identified that a lot of collections / collection types will "break" if an element or key is mutated.
In a lot of cases, immutability is a security requirement. For instance, in an environment where you are running untrusted code in a sandbox, any case where untrusted code could pass a StringBuilder instead of a String to trusted code is a potential security problem1.
In a lot of cases, the reason is backwards compatibility. The CharSequence interface was introduced in Java 1.4. Java APIs that predate Java 1.4 do not use it. Furthermore, changing an preexisting method that uses String to use CharSequence risks binary compatibility issues; i.e. it could prevent old Java code from running on a newer JVM.
In the remainder it could simply be - "too much work, too little time". Making changes to existing standard APIs involves a lot of effort to make sure that the change is going to be acceptable to everyone (e.g. checking for the above), and convincing everyone that it will all be OK. Work has to be prioritized.
So while you find this frustrating, it is unavoidable.
1 - This would leave the Java API designer with an awkward choice. Does he/she write the API to make (expensive) defensive copies whenever it is passed a mutable "string", and possibly change the semantics of the API (from the user's perspective!). Or does he/she label the API as "unsafe for untrusted code" ... and hope that developers notice / understand?
Of course, when you are designing your own APIs for your own reasons, you can make the call that security is not an issue. The Java API designers are not in that position. They need to design APIs that work for everyone. Using String is the simplest / least risky solution.
See http://docs.oracle.com/javase/6/docs/api/java/lang/CharSequence.html
Do you notice the part that explains that it has been around since 1.4? Previously all the API methods used String (which has been around since 1.0)

why linethrough in code of new Date

I am using netbeans 7.2. the IDE is applying a line-through to a class name, what does it means and how can I resolve it?
Date cookiedate = new Date(timeStamp);
see the shot how its looking
I suspect it means it's deprecated. See here for more info.
Java provides a way to express deprecation because, as a class
evolves, its API (application programming interface) inevitably
changes: methods are renamed for consistency, new and better methods
are added, and fields change. But such changes introduce a problem.
You need to keep the old API around until developers make the
transition to the new one, but you don't want them to continue
programming to the old API.
The ability to deprecate a class, method, or member field solves the
problem.
I would suggest using Joda-Time instead (with respect to the suggestions made by other posters here), since the Date/Calendar stuff that isn't deprecated is such a pain to use (non-untuitive api, mutable, thread-unsafe)
new Date(timeStamp);
You are using parameterized constructor of Date class which is deprecated, so you see that line cross. In fact most of the methods of Date class is now deprecated.
See documentation of Date class which clearly marks the parameterized constructor as Deprecated.
Date(String s)
Deprecated.
As of JDK version 1.1, replaced by
DateFormat.parse(String s).
I would rather suggest to use Joda Time API if you want to make your life easier while working with Dates.
It means the API you are invoking is deprecated, you should use Calendar API for example or if you are looking for a more sophisticated API I suggest to use Joda
Linethrough means it is deprecated. There is some other class/method available in place of that class/method. And also Netbeans shows somewhere around that deprecated class/method what you can use use instead of it if you have javadoc set up in it

Developing a simple utility class( like a Date class )in java

I am a college student.
In our college we have to develop a simple Date class in Java similar to the one available in java.util package.
If we do that then what are the methods we can implement in that class,
Since most of the methods are deprecated in original Date class.
I saw the original Date class definitions in java/util/Date.java. Being a beginner to java, I could not understand the concepts of Serializable, Cloneable, Comparable ,and many variables like fasttime.
It will be good if we can implement this date class simply (since we have to develop this code as a test with in 3 hours at lab.)
Whether it is necessary to implement those concepts in a simple Date class.
If I take it as a Project and start developing the whole Date utilities,
then that code will run to many pages
and I cannot finish it with 3 hours for our lab session.
So someone please guide me....
I have doubts about....
Whether it is possible to create a utility class similar to Date class with a simpler implementation.
If we do that, then what are the methods we can implement in that class , since most of the useful methods are deprecated in the original date class.
Thanks in advance.
Serializable means the class can be Serialized to a transportable binary form.
Clonable means the class can be cloned, this is very tricky to get right, mainly because of inheritance and mutability concerns.
Comparable means the class supports being compared to other classes of the same type.
Of these Comparable is the only one that requires any code to function, it is also probably the only one that is any use in your scenario.
Serializable is what is called a Marker Interface it doesn't require any code to cause anything to happen since it doesn't have any methods to implement. It just exists to mark the object as supporting something and another class and check for this interface and do things based on its existence.
Cloneable is something you want to stay away from if at all possible. Cloning objects in Java is not straight forward, has lots of gotchas and generally behaves in the most non-intuitive ways imaginable. If you really want to know about this, learn about this, read this article.
Comparable is very valuable, it lets you compare to like objects to see if one is less than, equal or greater than another. This is a requirement for sorting and Collections classes that support Comparators. Comparators can be thought of as stand alone implementations of Comparable that can be plugged into other classes to control how objects are compared.
java.util.Date is a tricky class, it appears to be a straight forward struct type class with some mutators and convenience methods, but the underlying problem domain for calendar data isn't that simple. Calendar math has lots of exceptional cases. That is why there are so many methods on java.util.Date that are deprecated, they produced wrong behavior in many cases.
For some more code to study, look at this temporal package I developed to wrap the standard Java Calendar with very basic Date, Time and TimeStamp classes, they all just delegate to an instance of Calendar for the actual calcuations.
NOTE: this library code pre-dates JodaTime for those of you that might complain about just not using that library.
You don't have to implement all the interfaces to have a simple working Date class.
I would suggest that you forget about Java's Date class and consider what you think is needed for a date class. For example:
Get/set day of month
Get/set month
Get/set year
Get day of week
toString()
Would give you a pretty good basic date class.
For the sake of completeness, I'll tell you what the interfaces are for. You can decide whether to implement them based on how much you have learned and the assignment's requirements:
Serializable is for saving your object to a stream. You actually don't need to do much work to implement it.
Comparable is for comparing objects (date1.compareTo(date2) should return an integer indicating whether date1 is before, after, or the same as date2).
Clonable is for creating a deep copy of the object.
Since this is a lab project, why don't you list down what kind of function a 'simple' Date class needs and should have. For example, toString() -- returns a string representation of a Data or toMilliSecond() -- returns the number of milliSecond from the reference time.

Categories