AmbGup
AmbGup

Reputation: 771

Is my static util method thread safe

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

Answers (4)

isnot2bad
isnot2bad

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:

  • If there is no such state, you're done - the method is thread safe.
  • If there is such state, you have to check if it is accessed in a thread safe manner.

(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

weston
weston

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

santhosh
santhosh

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

AlexR
AlexR

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

Related Questions