当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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?

网友答案:

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: