如何确保实用静态方法的线程安全? [英] How to ensure thread safety of utility static method?

查看:482
本文介绍了如何确保实用静态方法的线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何通用的方法或规则可以确保我们可以确保在任何应用程序的各种Utility类中专门使用的静态方法的线程安全性。在这里,我想特别指出Web应用程序的线程安全性。

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.

如果我有一个实用工具方法来操作 java.util.Date ,那么该方法接受一个实例 java.util.Date ,那么此方法不是线程安全的。那么如何在不改变参数传递方式的情况下使其线程安全?

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
    }   
}

同样是类 javax.faces.context.FacesContext 可变吗?将此类的实例传递给此静态实用程序方法是否可以安全?

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?

推荐答案


它是众所周知,使用不可变对象作为参数的静态方法是线程安全的,而可变对象则不是。

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.

我强烈建议你阅读 Java Concurrency in Practice ,或者类似于Java中的线程安全的书。这是一个复杂的主题,无法通过一些StackOverflow答案正确解决。

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.

这篇关于如何确保实用静态方法的线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆