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