Reputation:
I know there are a lot os posts about how to get the current time in java. But im planning to code a getAge Method in a Persona class. The problem is, I need to get the current time each time method is called. Let's say a billion clients execute getMethod(with miliseconds, perhaps seconds of difference), a billion of objects will be created for such a simple thing. The only thing I did was create a member static in Person, so Person will share the instace. But this doesnt prevent the object creation.
public class Person{
//Some Attributes
private static Calendar now;
private Calendar birthDate;
public short getAge(){
now = Calendar.getInstance();
return (short) (( now.getTimeInMillis() - birthDate.getTimeInMillis())/ 31536000000L;
}}
If you know some library that have this implemented without the waste of such heap size. Please tell me.
Thanks.
Upvotes: 6
Views: 13502
Reputation: 23443
With the time stamp obtained through optimized means, what additional processing / overheads will be required to make the obtained time stamp meaningful?
http://joda-time.sourceforge.net
If you would like a library to work with date and time, go with Joda Time. I wouldn't bang on any work around.
DateTime dt = new DateTime(); // current time
I suggest that if performance is a key concern / limiting issue that you run tests to ensure that any work around that you accept achieves non-functional results that outweigh code readability.
Upvotes: 0
Reputation: 785316
You can also create a Calendar instance once and keep calling:
calendar.setTimeInMillis ( System.currentTimeMillis() );
to set the current time in calendar instance and use that calendar object to do any date calculation.
Upvotes: 6
Reputation: 46219
No need to create a Calendar
, you can get a long
from the static method
System.currentTimeMillis();
Upvotes: 9