• Post Reply Bookmark Topic Watch Topic
  • New Topic

java.util.logger. SimpleFormatter  RSS feed

 
Alex Shepard
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings,

Can someone help me understand why java.util.logger. SimpleFormatter (class name mangled to get beyond 30 char word limit) uses a StringBuffer inside of a synchronized routine? My understanding is that setting a method synchronized locks it down so that only one thread can access it at a time. If that's the case, why not use the faster but not thread-safe StringBuilder? Or am I missing something?

Thanks,
alex
 
Henry Wong
author
Sheriff
Posts: 23282
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can make this argument for any StringBuffer that is declared in a local variable -- and not copied anywhere else. Why is there a need to use the symchronized version when there is a faster non-synchronized one? A possible answer is, because this code was written before Java 1.5. Or the programmer was too used to pre-Java 1.5 techniques.

Interestingly, you can't make the argument for the case you stated. Just because one method that uses the stringbuffer is synchronized doesn't mean that the use of the buffer is threadsafe. You need to confirm that every case that uses the buffer is synchronized with the same lock -- and then the answer is probably ... see previous paragraph.

Henry
 
Alex Shepard
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry,

Thanks for your response.

In this case, the StringBuffer is declared in the body of the synchronized function, and the function returns a stringified version of the StringBuffer.

I figured the pre-1.5 answer was likely, just wanted to make sure that I wasn't misunderstanding how local variables are treated in synchronized methods.

Thanks again,
alex
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!