How to ensure thread safety of utility static method?

73,323

Solution 1

It is well known that static methods with immutable objects as parameters are thread safe and mutable objects are not.

I would contest this. Arguments passed to a method are stored on a stack, which is a per-thread idiom.

If your parameter is a mutable object such as a Date then you need to ensure other threads are not modifying it at the same time elsewhere. But that's a different matter unrelated to the thread-safety of your method.

The method you posted is thread-safe. It maintains no state and operates only on its arguments.

I would strongly recommend you read Java Concurrency in Practice, or a similar book dedicated to thread safety in Java. It's a complex subject that cannot be addressed appropriately through a few StackOverflow answers.

Solution 2

Since your class does not hold any member variables, your method is stateless (it only uses local variables and the argument) and therefore is thread safe.

The code that calls it might not be thread safe but that's another discussion. For example, Date not being thread safe, if the calling code reads a Date that has been written by another thread, you must use proper synchronization in the Date writing and reading code.

Solution 3

Given the structure of the JVM, local variables, method parameters, and return values are inherently "thread-safe." But instance variables and class variables will only be thread-safe if you design your class appropriately. more here

Solution 4

I see a lot of answers but none really pointing out the reason.

So this can be thought like this, Whenever a thread is created, it is created with its own stack (I guess the size of the stack at the time of creation is ~2MB). So any execution that happens actually happens within the context of this thread stack. Any variable that is created lives in the heap but it's reference lives in the stack with the exceptions being static variables which do not live in the thread stack.

Any function call you make is actually pushed onto the thread stack, be it static or non-static. Since the complete method was pushed onto the stack, any variable creation that takes place lives within the stack (again exceptions being static variables) and only accessible to one thread.

So all the methods are thread safe until they change the state of some static variable.

Solution 5

I would recommend creating a copy of that (mutable) object as soon as the method starts and use the copy instead of original parameter.

Something like this

public static Date getNormalizeDate(Date date) {
    Date input = new Date(date.getTime());
    // ...
}
Share:
73,323

Related videos on Youtube

Tapas Bose
Author by

Tapas Bose

Java developer.

Updated on April 12, 2021

Comments

  • Tapas Bose
    Tapas Bose about 3 years

    Is there any general way or rules exits by which we can ensure the thread safety of static methods specifically used in various Utility classes of any applications. Here I want to specifically point out the thread safety of Web Applications.

    It is well know that static methods with Immutable Objects as parameters are thread safe and Mutable Objects are not.

    If I have a utility method for some manipulation of java.util.Date and that method accepts an instance of java.util.Date, then this method would not be thread safe. Then how to make it thread safe without changing the way of parameter passing?

    public class DateUtils {
    
        public static Date getNormalizeDate(Date date) {
            // some operations
        }   
    }
    

    Also is the class javax.faces.context.FacesContext mutable? Is it thread safe to pass an instance of this class to such static utility method?

    This list of classes, instances of which can be or cannot be passed as parameters, could be long; so what points should we keep in mind while writing codes of such utility classes?

    • Tapas Bose
      Tapas Bose over 11 years
      Why down vote and one close request? Is it a wrong question?
    • Andrew Logvinov
      Andrew Logvinov over 11 years
      Have you considered making this static method synchronized?
    • Tapas Bose
      Tapas Bose over 11 years
      @AndrewLogvinov yes I have thought. But I don't want to make a method synchronized without knowing why I am doing it. In what situations should we make a static method synchronized?
    • Duncan Jones
      Duncan Jones over 11 years
      @TapasBose That last comment question can probably spawn a book or two. I would recommend Java Concurrency in Practice.
    • Andrew Logvinov
      Andrew Logvinov over 11 years
      Well, you need to synchronize methods (both static and instance) which access mutable variables. In case of utility classes I don't see much need in it since they should be stateless.
  • Saurabh Patil
    Saurabh Patil almost 7 years
    This sounds good for Date, but won't be possible for custom objects, especially if it is a 3rd party custom object that he can't edit.
  • Gaurav
    Gaurav over 5 years
    @Duncan: What other books on multithreading can you recommend ?
  • R Kaja Mohideen
    R Kaja Mohideen over 5 years
    If you can't clone in case of 3rd party - you cant do much except asking that 3rd party to make their class instances thread-safe.
  • Shrikant Prabhu
    Shrikant Prabhu over 5 years
    There is multithreading in java course on educative.io educative.io/collection/5307417243942912/…
  • MasterJoe
    MasterJoe almost 4 years
    IMO, read xyz book is generally not a helpful answer. Why not address the specific question in more detail instead of throwing a whole book at a person ?