StringBuffer can handle multiple threads through synchronization If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.
Can anyone explain me when does the Multithreading happen? Do we create threads in our program implementing runnable interface or extending Thread class or is it OS based?.
The threading can happen any number of ways. If you are creating threads (e.g.
extends Thread) or if you are creating objects that get passed off to a threading model of some kind (e.g.implements Runnable) or even if you just have code somewhere that handles something like events (e.g. a callback function). How the threads are created isn’t important. In any case, when you have something like this:You know that is thread safe. Any access to the
StringBuilder‘sappend()method doesn’t need to by synchronized. However, if you have something like this (just an example):Here, you can see that more than one “thread” of execution could call
someMethod(), and since they would all be access theStringBuffer, it needs to be synchronized. It could be the case that only one thread ever calls the method at any one given time, but the way this is written doesn’t prohibit 2 threads calling it at the same time. If aStringBuilderis used (not thread safe) you’re likely to run into problems.