Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Necessity of synchronized on local variable

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?

like image 860
qqilihq Avatar asked Aug 19 '13 16:08

qqilihq


People also ask

Why is synchronized needed?

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.

Why is synchronization necessary explain with example?

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.

What is the need of synchronizing 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.

Why synchronized block is required?

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.


2 Answers

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.

like image 103
jtahlborn Avatar answered Oct 27 '22 21:10

jtahlborn


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.

like image 39
Sotirios Delimanolis Avatar answered Oct 27 '22 23:10

Sotirios Delimanolis