Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is the below static utility method Threadsafe

I am writing a static utility method.I know methods isEmpty() , isNew() are threadsafe..In getTotal(...)method I am using StringBuilder as parameter alomg with String and int.StringBuilder is mutable. Is getTotal() threadsafe.If so explain why it is even though StringBuilder is mutable . But I am not sure if getCharge() is thread safe bcz its invoking the method getTotal(). Can someone tell if it is threadsafe or not

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;
     }
}
like image 505
sarath Avatar asked Sep 26 '26 00:09

sarath


2 Answers

It is. You are not using any fields / variables that are not method scoped and all the parameters to the methods are immutable, so therefore it is thread-safe.

The only thread-safety risk in a method that does not use any non-method scoped variables is if the parameters are mutable and therefore could be modified by another thread. Since primitives and String are immutable, you are good.

EDIT: Posted comment:

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

like image 140
John B Avatar answered Sep 28 '26 15:09

John B


Your static methods don't have any state between calls. All state passed by parameter...so its thread safe.

like image 42
user1697575 Avatar answered Sep 28 '26 15:09

user1697575



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!