• Post Reply Bookmark Topic Watch Topic
  • New Topic

Referenced methods in synch block  RSS feed

 
J.D. Thompson
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Example code

private StringBuffer m_buffer=new StringBuffer();


public synchronized method1(String value)
{
m_buffer.append(value);
method2();
}

public method2()
{
System.out.println(m_buffer.toString());
m_buffer.setLength(0);
}

Is m_buffer protected during one threads call from all other threads in method2??

Thank you in advance for your prompt reply.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. method1 is synchronized, but method2 isn't, and it is public. So any code can simply call method2 directly. The StringBuffer methods themselves are synchronized, but it's still possible to add something to it between retrieving its contents and setting the length to 0.
 
J.D. Thompson
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ty very much!!

Have a great day!!

JD
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!