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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)