Necessity of synchronized on local variable

旧街凉风 提交于 2019-12-04 04:49:33

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.

getBuffer() returns a StringBuffer, and according to the documentation a StringBuffer is already synchronized:

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

This means that synchronizing again on the StringBuffer is totally overkill. Changes to the StringWriter will automatically be synchronized because it uses the synchronized StringBuffer internally.

Since the StringWriter instance is local to the method call, it's impossible to have multiple threads accessing the same instance at the same time, which also makes synchronization unnecessary.

It is a bug. Every thread creates its own local variable in the method and synchronizes on it.Each time entering the method threads create their own object-monitor which cannot be held by another thread because it's local and lives only on thread's stack!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!