简体   繁体   中英

synchronization on the same reference more than once in java

I am modifying an existing java multithreaded app. Within each thread, the application retrieves an outputstream object through a synchronized method call (which I am thinking of replacing with enum or readwritelock). Once the thread has acquired the reference, it then proceeds to synchronize on the outputstream again before passing a byteArrayOutputStream to it for writing out). Any thoughts on how I can go about optimizing it if at all - I do see some threads in monitor state when there is slightly high load (increasing thread count is not something I am considering). Any useful suggestions would be quite welcome.

Within each thread, the application retrieves an outputstream object through a synchronized method call (which I am thinking of replacing with enum or readwritelock).

This seems reasonable. Each thread is blocking with each other just to get the appropriate output stream. You might be able to replace this with a ConcurrentHashMap if the mapping from thread-info to OutputStream can be done in a map.

Once the thread has acquired the reference, it then proceeds to synchronize on the outputstream again before passing a byteArrayOutputStream to it for writing out)

Once it has the appropriate OutputStream it locks on it to guarantee unique access to the stream. You might want to make sure that what is underneath the stream is not already synchronized (typically not the case) but otherwise this seems reasonable.

Any thoughts on how I can go about optimizing it if at all

Your program is most likely going to be IO bound long before the cost of the synchronization makes a difference. Unless a profiler is telling you that there is performance problems with the synchronization, I would focus your optimization efforts elsewhere.

As far as I can see there are two synchronized calls here:

  • the call to obtain an outputstream (synched on some object)
  • the call to ByteArrayOutputStream.writeTo (synched on some outputstream)

The latter basically calls outputstream.write which you should not do from different threads concurrently, so there's no way to avoid the second.

As for the first, with the information you have given it is not possible to say whether it makes sense to invest time into getting rid of synchronized, or even whether it is necessary. Replacing it with a read-write-lock can make sense -- unless basically everyone is writing. Conversely, if there are only readers you can (possibly) get rid of the lock altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM