Search code examples
multithreadinglockingsingletonsynchronized

Appropriate use of synchronizing or locking a segment of code


Given a singleton class Employee with 2 methods int getSalary() void updateSalary(int increment)

Do I need to synchronize or lock both these functions or use atomic salary variable? If yes then the question is that in this way we would have to synchronize all the functions that we define in multithreaded environment. So, why not just make synchronized a standard as today no real world application would be single threaded?


Solution

  • With Singleton, we always have to very careful because, singleton object being a single instance naturally, can be shared between threads. Making functions synchronized is one way, and it is not efficient way. We need to think about other aspect of concurrency, like immutability Atomic classes.

    class Employee {
    
         //singleton instantiation 
         private final AtomicInteger sal  = new AtomicInteger(0);
         
         int getSalary(){
             return sla.get();
         }
         void updateSalary(int increment){
            sla.add(increment);
         }
    }
    

    This will solve, we do not need to synchronize every method of the singleton class.

    We do not have to mark every function of every class to be synchronized, but always have to be careful if a function is modifying a state or reading a state and could be concurrently invoked, in such cases start thinking about synchronization. But, with singleton classes we always have to be careful.