• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to understand StringBuffer is thread safe and StringBuilder is not by example output?  RSS feed

 
Ganish Patil
Ranch Hand
Posts: 529
19
Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here I've created two methods which are not thread safe so I won't get counter 0 everytime as It should be. When I synchronize those methods yes I do get 0 everytime.
Output: Not 0 everytime, it varies.
My Question: Same way can anyone tell me how I should write an example of StringBuffer and StringBuilder so I can understand by getting results that StringBuffer is thread safe and StringBuilder is not.

I did for performance of both and found StringBuilder is bit faster than StringBuffer here is the code:Output:Time Taken by StringBuffer is: 66 ms
Time Taken by StringBuilder is: 28 ms

 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thread safety is said when the object can be used by several threads in a concurrent way and the outcome is as expected.



run:
7087
7088
BUILD SUCCESSFUL (total time: 0 seconds)
 
Ganish Patil
Ranch Hand
Posts: 529
19
Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much Ivan Jozsef Balazs. I think I solved that please check this. Below program which appends 6 "A"'s and immediately deletes 5 "A"'s after appending in StringBuilder. Two threads will try to do this so each loop in run will add one "A" to StringBuilder strBuilder so total of two thread it should be 50000 * 2 = 100000 but as StringBuilder is not thread safe so both thread try to access simultaneously that causes failure of appending and deleting "A" so result varies here. Same program I did for StringBuffer which results as expected because it is thread safe so only one thread appended and deleted at a time. No exception generated.

StringBuilder Program Expected Output is 100000 but give different output because StringBuilder is not thread safe.
Output:
A wasn't at index 0 null
Final StringBuilder Length: 99981 ( sometime 99987. It varies)

StringBuffer Program
As expected because it is thread safe. Same output everytime.
Output:
Final StringBuffer Length: 100000
Hope I'm on correct path
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ganish Patil wrote:
Hope I'm on correct path


Yes.
 
Ganish Patil
Ranch Hand
Posts: 529
19
Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Netbeans IDE Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!