How to ensure thread safety of utility static method?

前端 未结 6 545
南笙
南笙 2020-12-04 07:30

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 w

6条回答
  •  时光说笑
    2020-12-04 07:58

    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.

提交回复
热议问题