Thread Safety and Shared Resources
Thread Safety and Shared Resources
I have been reading that code that is safe to call by multiple threads simultaneously is called thread safe. If a piece of code is thread safe, then it contains no race conditions. Race condition only occur when multiple threads update shared resources. Therefore it is important to know what resources Java threads share when executing.
I have a class as below;
public class ClassA
JSONObject data = new JSONObject();
public void methodA(Map<?, ?> resultMap, String Url)
try
data.put("request_id", resultMap.get("request_id"));
data.put("account", resultMap.get("account"));
postToCallBackUrl.sendToCallBackUrl(data, Url, resultMap);
catch (JSONException e)
logger.error(e);
public void methodB(Map<?, ?> resultMap, String Url)
try
data.put("request_id", resultMap.get("request_id"));
data.put("name", resultMap.get("name"));
postToCallBackUrl.sendToCallBackUrl(data, Url, resultMap);
catch (JSONException e)
logger.error(e);
My question is on the usage of JSONObject data = new JSONObject()
, is it thread safe as currently declared?
JSONObject data = new JSONObject()
Or do I need to declare it in every method?
The data in all the methods is passed to another class postToCallBackUrl
and a specific method sendToCallBackUrl(data, Url, resultMap)
.
postToCallBackUrl
sendToCallBackUrl(data, Url, resultMap)
Anyone advice?
1 Answer
1
This looks wildly thread-unsafe. The javadoc for JSONObject
explicitly states that the class is not thread safe. Since data
can be accessed from the methods without any sort of synchronization, this is not a safe usage.
JSONObject
data
But the code doesn't even look safe for one thread to use, because state from one method invocation affects other method invocations.
Yes, create a new JSONObject
as a local variable in the methods. It then becomes thread safe by confinement, and you retain no state between method invocations.
JSONObject
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.