Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring : Is this member variable thread-safe?

@Service    
public class InfoService {
    private Info currentInfo;

    public void initInfo(String data) {
        currentInfo = new Info(data);
    }

    //blarblar...
}

If this is not thread-safe, my service methods should be changed to hold "currentInfo" as its parameter. I don't want to make duplicate parameter code, so I make it as member variable of service. Of course, this code works perfectly on me, but I worry about this can be thread-danger.

"currentInfo" can be thread-danger?

like image 669
planetes853 Avatar asked Jun 26 '26 13:06

planetes853


1 Answers

after initialization you would have singleton instance of this class, now imagine two threads have reference to this object,

thread-1: sets currentInfo and starts calculating something based on it (I assume you are using it in other calculation with your //blarblar...)

thread-2: After thred-1 starts using it meanwhile thread-2 resets it

like image 83
jmj Avatar answered Jun 29 '26 03:06

jmj



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!