有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是以下静态实用程序方法Threadsafe

我正在编写一个静态实用程序方法。我知道方法isEmpty()和isNew()是线程安全的。。在getTotal(…)方法我使用StringBuilder作为参数alomg with String和int.StringBuilder是可变的。getTotal()是线程安全的。如果是,请解释为什么StringBuilder是可变的。 但是我不确定getCharge()是否是线程安全的bcz,因为它调用了getTotal()方法。 有人能告诉我它是否是线程安全的吗

public class NewStringUtils {

    public static boolean  isEmpty(String s){
        return (s == null || s.trim().length()==0);
    }

    public static boolean isNew(String code){
        return( "1009".equals(code) || "1008".equals(code) );
    }
    //StringBuilder is  mutable  -- is the below method threadsafe 
    public static int getTotal(StringBuilder sb,String oldCode ,int a, int b){
        //Is it Threadsafe or not .If so  just bcz every thread invoking this method will have its own copy and other threads can't see its value ?? 
        int k =0;
        if("1011".equals(oldCode) && "1021".equals(sb.toString()) {
            k = a+b;
        }
        return k;
    }
    // is the below method threadsafe 
    public static  int getCharge(String code,String oldCode,int charge1,int charge2){
        int total =0;
        StringBuilder sb = new StringBuilder("1021");
        if(!NewStringUtils.isEmpty(code)){

            if(NewStringUtils.isNew(code)){
                //here invoking a static method which has StringBuilder(Mutable) as a         parameter
                total  = NewStringUtils.getTotal(sb,oldCode,charge1,charge2);
            }
        }

        return total;
     }
}

共 (4) 个答案

  1. # 1 楼答案

    所有变量都是局部变量,线程之间没有共享变量(静态变量,因为它是静态方法),传递的引用要么是原语,要么是不可变类的不可变项。因此,它是线程安全的

  2. # 2 楼答案

    静态方法在调用之间没有任何状态。参数传递的所有状态。。。所以它是线程安全的

  3. # 3 楼答案

    是的。您没有使用任何不属于方法范围的字段/变量,并且方法的所有参数都是不可变的,因此它是线程安全的

    在不使用任何非方法作用域变量的方法中,唯一的线程安全风险是参数是可变的,因此可能被另一个线程修改。因为原语和String是不可变的,所以您很好

    编辑:发表评论:

    How about this: if a method (static or otherwise) uses only method-scoped variables, has only immutable parameters and only invokes other thread-safe methods then it must be thread-safe

  4. # 4 楼答案

    是的ints按值传递。和Strings是该方法的参数。您没有使用方法之外的任何字段

    编辑

    如果要使用StringBuilder而不是String,则需要在StringBuilder对象上进行同步

    public someMethod(StringBuilder sb, ...) {
        synchronized(sb) {
    
            //this will make sb thread safe.
            //but do this everywhere you access this StringBuilder Object.
    
        }
    }