Java Object Level Synchronization

Object Level Synchronization comes into the picture when two or more using the same Object Or shared a resource across the multiple threads. Without synchronization there is a heavy chances of the data might go into inconsistent state.

Synchronization is the only way to avoid the data inconsistency of a Shared resource or an object, synchronization is a concept which prevents accessing the shared resource or an object by multiple threads at a time.

Synchronization allows only one thread can access the resource at a time. In Java synchronization can be achieved by using the keyword synchronized.

Every object in a Java possesses a lock, synchronized block or method allows to acquire a lock of an object by only one thread at a time. Once the thread is completed the execution of that synchronized block or method then the lock of that object will be released for other threads.

Object Level lock example

public class ReadAndIncrementInteger extends Thread {

	public IntegerClass objectLock;

	public static void main(String[] args) {
		IntegerClass objectLock = new IntegerClass();

		Thread thread1 = new ReadAndIncrementInteger(objectLock);
		Thread thread2 = new ReadAndIncrementInteger(objectLock);

		thread1.start();
		thread2.start();
	}

	public ReadAndIncrementInteger(IntegerClass objectLock) {
		this.objectLock = objectLock;
	}

	public void run() {

		synchronized (this.objectLock) {

			while (this.objectLock.getInteger() < 10) {

				this.objectLock.setInteger(this.objectLock.getInteger() + 1);
				System.out.println("Integer Value  : " + this.objectLock.getInteger());
			}
		}
	}

}

class IntegerClass {

	public Integer integer = new Integer(0);

	public Integer getInteger() {
		return integer;
	}

	public void setInteger(Integer integer) {
		this.integer = integer;
	}

}
output
Integer Value  : 1
Integer Value  : 2
Integer Value  : 3
Integer Value  : 4
Integer Value  : 5
Integer Value  : 6
Integer Value  : 7
Integer Value  : 8
Integer Value  : 9
Integer Value  : 10