new DecimalFormat(pattern) vs decimalFormat.applyPattern(pattern)? - java

I was working with DecimalFormat today and found a method inside it applyPattern() so whenever I had to use DecimalFormat or SimpleDateFormat I used to assign them as under:
private static final DecimalFormat dFormat = new DecimalFormat(pattern);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
But now I applied another approach. Instead of creating multiple static final Decimal or Date formats I created just one variable for each of them. And then applied them on the fly as under:
private static final DecimalFormat dFormat = new DecimalFormat();
private static final SimpleDateFormat dateFormat = new SimpleDateFormat();
and whenever I need to apply a new pattern for any one of them I apply it like this:
dFormat.applyPattern(Constants.somePattern);
dFormat.format(SOMETHING);
So during a code review it was commented that this approach is not good for performance. But my point is that I am making my code more flexible as well as I am calling few new's so less objects are being created.
could someone throw some light on this point.

Related

Java 8 best way to parse text date to millisecond timestamp

I want to create a Java class with thread-safe static methods to parse dates. I understand that some of the Java 7 (and earlier) date time classes are not thread-safe. What is the best thread-safe implementation in Java 8 of this functionality:
String text = "5/16/2008";
long timestamp = DateUtil.getTimestamp(text);
In Java 7 and earlier, you would do this:
public class DateUtil {
public static long getTimestamp(String text) {
DateFormat df = new SimpleDateFormat("M/d/yyyy");
df.setTimeZone(TimeZone.getTimeZone("America/New_York"));
long timestamp = df.parse(text).getTime();
return timestamp;
}
}
But instead of creating a new instance of DateFormat for every call, I want to share a single static instance for all calls to this static getTimestamp method. My understanding is that this is not thread-safe.
One key requirement is that the text I want to parse has a short date like "5/16/2008" without HH:mm:ss resolution.
I also don't want to use a third party library like Joda-Time, but rather only standard Java 8 classes.
Here's a version of your code refactored to use the java.time.* package in Java 8. It uses a static final formatter instance, which is thread-safe and immutable, unlike java.text.SimpleDateFormat.
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class DateUtil {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
public static long getTimestamp(String text) {
LocalDate localDate = LocalDate.parse(text, formatter);
return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant()).getTime();
}
}
You can use joda-time lib. DateTime is immutable - and once created the values do not change, so class can safely be passed around and used in multiple threads without synchronization.
A companion mutable class to DateTime is MutableDateTime, of which the class can be modified and are not thread-safe.
DateTimeFormatter formatter = DateTimeFormat.forPattern("M/d/yyyy'T'HH:mm:ss.SSSZZ")
.withLocale(Locale.ROOT).withChronology(ISOChronology.getInstanceUTC());
DateTime dt = formatter.parseDateTime(text);
Reference of DateTimeFormatt: DatetimeFormat api.
As stated in ck1's answer, usage of java.time API is a better approach than the legacy classes. DateTimeFormatter is immutable and thread-safe, and using a static final instance of it will solve your problem.
The only part where I differ from that answer is in the code , where the Date class is used to get the time. I would like to take the java.time approach here as well. Below is my version :
public class DateUtil {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yyyy");
public static long getTimestamp(String text) {
LocalDate localDate = LocalDate.parse(text, formatter);
return Instant.from(localDate.atStartOfDay(ZoneId.systemDefault())).toEpochMilli();
}
public static void main(String[] args) {
String text = "5/16/2008";
long timestamp = DateUtil.getTimestamp(text);
System.out.println(timestamp);
}
}

convert mutable variable to immutable in java with less pain

sometime i have no choice to use mutable variable instead of immutable variables i know how many ways can create immutable vars but i wonder this way also correct its really convert mutable to immutable and i dont use concurrency or multithreading in my code just Curious?
public class Config implements FindIt {
....
private final class DateHolder{
private final Date dateContainDateObject;
DateHolder(String date) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
dateContainDateObject = dateFormat.parse(date);
}
public Date getDate(){
return dateContainDateObject;
}
}
}
this is nested class and i use it like
private DateHolder holder;
and fill the holder variable in Config constructor class so holder variable are ThreadSafe ?
Date is a mutable object. Making it final means you can't change the reference to it, but you can still change what's at the reference (java.util.Date/Calendar nastiness strikes again, switch to the Java 8/Joda Time way if you can).
Don't expose any references to the Date member to the outside world. Instead make a defensive copy and pass that back instead. You might consider saving the time value as a final long instance member and only instantiating a Date when you need it.
can say is safe when you make class private and non-static, when you create form Config class you have only one DateHolder .
http://www.javapractices.com/topic/TopicAction.do?Id=29
why is static inner class singleton thread safe
http://www.javatpoint.com/how-to-create-immutable-class

What does "The constructor FastDateFormat(String, TimeZone, Locale) is not visible" mean?

SimpleDateFormat lets me do this:
SimpleDateFormat mySimpleDateFormatter = new SimpleDateFormat("dd-MMM-yyyy");
But FastDateFormat doesn't:
import org.apache.commons.lang3.time.FastDateFormat;
//...
FastDateFormat myFastDateFormatter = new FastDateFormat(str, tz, loc);
Now it complains that:
"The constructor FastDateFormat(String, TimeZone, Locale) is not visible"
The error message doesn't lead me anywhere... What did I do wrong?
Unlike, Java's SimpleDateFormat, you cannot simply declare an instance of Apache's FastDateFormat class.
Instead, FastDateFormat statically serves up instances of the class via the Factory Method Pattern - you must call the class' static method getInstance, as in the following:
String dateFormatPattern = "yyyy-mm-dd'T'HH:mm:ss.SSSZ";
FastDateFormat myFastDateFormatter = FastDateFormat.getInstance(dateFormatPattern);
Now you have a myFastDateFormatter loaded configured with that date format pattern.
You can use it to parse strings into real Dates, assuming those strings conform to your dateFormatPattern:
String dateString = "2014-04-03T14:02:57.182+0200";
Date myDate = myFastDateFormatter.parse(dateString);

Malicious code vulnerability - Field should be package protected

Sonar is giving me the message:
Malicious code vulnerability - Field should be package protected for
static array FORMATS.
Why is this code considered malicious? I have a public class to store all the constants.
public class Constants
{
/*
all the public static final constants of primitive datatypes for which
there is no sonar warning.
*/
public static final String[] FORMATS = new String[] {
"yyyy-MM-dd HH:mm:ss.S z",
"yyyy-MM-dd HH:mm:ss.S"
}
Probably because another piece of code could execute:
Constants.FORMATS[0] = "SOME GARBAGE";
And break the rest of your code.
In other words your array is constant but not its content.
Examples of alternatives:
you can store each format as a separate String constant
you can use an immutable list instead: public static final List<String> FORMATS = Collections.unmodifiableList(Arrays.asList("yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S"));
make it a method:
public static String[] formats() {
return new String[] { "yyyy-MM-dd HH:mm:ss.S z", "yyyy-MM-dd HH:mm:ss.S" };
}
ignore the warning if you are confident that (i) only your own code will access that class and (ii) there is no way you/your colleagues would even think of reassigning one of the values.

Should I use the "final" modifier when creating Date objects? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should one use final?
When should Java programmers prefer to use
final Date now = new Date();
over
Date now = new Date();
Apart from deciding if a variable should be final or not which is covered in other posts, I think the problem with final Date now = ..., is that although the reference to now will not change (it is final), its value might. So I find this a little misleading for developers who don't know that Date is mutable.
For example, you could write:
public static void main(String[] args) {
final Date now = new Date();
System.out.println(now);
now.setHours(5);
System.out.println(now);
}
and get 2 different dates out of your final date...
Now this is true for any mutable variable (the content of final List<String> l can change too), but I think in the case of a Date, it is way too easy to assume immutability.
A better solution would be using the joda time library:
final DateTime now = new DateTime();
in this case, now is immutable and won't change (reference & value).
In Java, a final variable is a variable whose value, once assigned, cannot be changed. You declare a variable final when that variable will be assigned a value, and you will never need to change that value.
When you use final keyword you can never change the value of variable.Same apply for date.
A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to an different object.
However the data within the object can be changed. So the state of the object can be changed but not the reference.
With variables, the final modifier often is used with static to make the constant a class variable.
Example:
class Test{
final int value=10;
// The following are examples of declaring constants:
public static final int BOXWIDTH = 6;
static final String TITLE = "Manager";
public void changeValue(){
value = 12; //will give an error
}
}
if your requirement is of this type than you can use final with date.
If you declare a field, which is read-only, and you want to have a class thread-safe - then you should use the final modifier. Sometimes you're forced to make a variable final, if it's used in an anonymous class. In all other cases it doesn't really matter.

Categories