• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Thread Safe

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Guys, For the following class


class TestClass
{
StringBuilder strBuilder = new StringBuilder()
public void appendString(String str)
{
strBuilder.append(str);
}
}


Does changing StringBuilder to StringBuffer enough to make the class Thread Safe? Or do I need to make the method synchronized to make it thread safe?
 
Bartender
Posts: 6663
5
MyEclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You can make it thread safe by

  • Synchronizing over the method and using string builder
  • Using a thread safe StringBuffer. But the notion of the thread safety can be misleading if you provide unguarded access to the StringBuffer.
  • Synchronize over a block of code and write to any internal data structure, which is pretty much like option 1


  • Since your class does not provide getter methods for the String (any type of String like String builder etc) the only worry here is about ensuring that the String is manipulated by one thread at a time and that its manipulation is visible to all other threads. Synchronization will help achieve that goal either with a synchronized class or by handling the synchronization outside the class.
    reply
      Bookmark Topic Watch Topic
    • New Topic