What is synchronization in java? Can a java class be synchronized?

Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non-synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.

Synchronization is implemented using monitors (monitorenter, monitorexit instructions). It provides mutual exclusion of locks over block of code called a critical section.

An example of method synchronization:

 public synchronized void method1() {
	// method code.

Synchronizing a block of code inside a method/function:

  public method2() {
	synchronized (this) {
	    // synchronized code here.

If you make all the methods in a java class as static synchronized, then the thread can access the methods only through the class reference and not through the ‘this’ reference. Therefore multiple threads accessing static synchronized methods will block each other and hence it will create view like synchronizing class. But doing this is very costly.