In the JSON-java library (org.json.JSONArray) I have found this code snippet with a synchronized
block around a method-local variable
public String toString(int indentFactor) throws JSONException {
StringWriter sw = new StringWriter();
synchronized (sw.getBuffer()) {
return this.write(sw, indentFactor, 0).toString();
}
}
I do not understand the necessity for the synchronization here, as the StringWriter
is only local to the given method (and, why the synchronization is on the Buffer). Is the synchronization really necessary here, and if, why?
Data synchronization ensures accurate, secure, compliant data and successful team and customer experiences. It assures congruence between each source of data and its different endpoints. As data comes in, it is cleaned, checked for errors, duplication, and consistency before being put to use.
Synchronization in java is the capability to control the access of multiple threads to any shared resource. In the Multithreading concept, multiple threads try to access the shared resources at a time to produce inconsistent results. The synchronization is necessary for reliable communication between threads.
Thread synchronization is the concurrent execution of two or more threads that share critical resources. Threads should be synchronized to avoid critical resource use conflicts. Otherwise, conflicts may arise when parallel-running threads attempt to modify a common variable at the same time.
A synchronized block ensures that a call to a method that is a member of an object occurs only after the current thread has successfully entered the object's monitor.
This may be a performance optimization. In the oracle jvm, re-acquiring an already held lock is very fast. Presumably, the write
call is making numerous calls into the StringBuffer. By locking before calling write
, the lock will be held through all of those calls instead of being released and re-acquired for each call.
The empty constructor for StringWriter
is
/**
* Create a new string writer using the default initial string-buffer
* size.
*/
public StringWriter() {
buf = new StringBuffer();
lock = buf;
}
Nothing is shared, therefore the synchronized
block is unnecessary.
Unless... write
delegates to another thread, but I seriously doubt that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With