Reputation: 771
I have a Util class with a utility methods as:
public static String formatAmount(String amount) throws Exception {
return String.format("%,.2f", Double.valueOf(amount));
}
Is this method thread safe? I am not modifying amount any where else.
Secondly, I have another method as.
private boolean checkIfDateIsAHoliday(org.joda.time.LocalDate date) {
boolean isHoliday = false;
.......
return isHoliday;
}
Is this method thread safe? I am not modifying date any where else.
Upvotes: 0
Views: 166
Reputation: 24464
Thread safety is all about accessing shared state. So if you want to know if a method is thread safe, you only have to check if it accesses state (=fields) that can also be accessed by other threads:
(See also http://tutorials.jenkov.com/java-concurrency/thread-safety.html)
Your first method does not access any shared state (String
is immutable, hence the parameter is thread-safe by itself). It calls two static methods (String.format
and Double.valueOf
) which might access shared state. Unfortunately, javadoc does not say anything concerning thread-safety of these two methods. Nevertheless we can assume that they are (otherwise almost all java applications were broken).
Your second method is thread safe concerning the code we can see (we can't argue about the code behind .....
). Reason: You're just modifying local state (stack variable isHoliday
). As local state cannot be accessed by other threads, this is thread-safe by definition.
Now just try to argue concerning the rest of your code (.....
)!
Upvotes: 1
Reputation: 54811
The first one is thread-safe because you are only reading an immutable variable String
.
Joda's LocalDate
is also immutable. Therefore, assuming you are not reading or writing mutable class or instance fields, this method is also threadsafe.
Upvotes: 0
Reputation: 484
For the First method it will be Thread safe But It won't be Thread Safe for the method you have declared in the second
Upvotes: 0
Reputation: 115418
As always the hell is in the small details. Your first method is thread safe because it definitely does not change state of any class.
Your seconds method is available only partially. I do not know what is written in your code instead of .......
. If you do not change state your any class there the method is thread-safe, otherwise it is not.
Upvotes: 5