我正在编写一个静态实用程序方法。我知道方法 isEmpty() , isNew() 是线程安全的。在 getTotal(...) 方法中,我使用 StringBuilder 作为参数 alomg 与 String 和 int.StringBuilder 是可变的。getTotal() 是线程安全的。如果是这样,请解释为什么即使 StringBuilder 是 mutable 也是如此。但我不确定 getCharge() 是否是线程安全的,因为它调用了 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;
}
}