Search code examples
javathread-safetystringbuffer

StringBuffer and Multithreading


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?.


Solution

  • 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:

    public String someMethod()
    {
        StringBuilder b = new StringBuilder();
        b.append("Some Method");
        return(b.toString());
    }
    

    You know that is thread safe. Any access to the StringBuilder's append() method doesn't need to by synchronized. However, if you have something like this (just an example):

    public class Test
    {
        StringBuffer b;
    
        public Test()
        {
            b = new StringBuffer();
        }
    
        public String someMethod()
        {
            b.append("Some Method");
            return(b.toString());
        }
    }
    

    Here, you can see that more than one "thread" of execution could call someMethod(), and since they would all be access the StringBuffer, 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 a StringBuilder is used (not thread safe) you're likely to run into problems.