Krivalar Tutorials 
Krivalar Tutorials


Java synchronized Keyword

<< final Keyword

volatile Keyword >>





synchronized keyword is used only when multiple threads are used in Java. Marking a method or block of code synchronized makes the object accessible for only one thread at a time. Whichever thread accesses the sychronized method or block of code, gets the lock on the object, on which it is invoked. Lock is released, when the thread exits the synchronized method or block

  • synchronized keyword can be used on Java methods and blocks.
  • synchronized keyword can not be used on variables, enum and nested classes.
  • synchronized keyword can not be used inside intertaces.
  • Top level classes and interfaces cannot marked synchronized.

synchronized method

Any thread which enters the synchronized method, locks the object on which it is invoked. Once the object is locked, other threads have to wait to access the object, until it is unlocked.

This means that other threads have to wait:

  • to invoke any method on that particular object.
  • to access any member of the object
public class HiThread{
	int count=0;
	//synchronized method
	 synchronized void roll() {
	 	count++;
	 }
}

synchronized block

Any thread which enters the synchronized block, locks the object on which it is invoked. Once the object is locked, other threads have to wait to access the object, until it is unlocked.

This means that other threads have to wait:

  • to invoke any method on that particular object.
  • to access any member of the object

For the synchronized block, we need to specify the object which needs to be locked by the thread which first accesses it.this keyword is used to indicate that the current object on which thread is invoked.

public class HiThread{
	 void generate() {
		 //synchronized block
		 synchronized(this) {
			 System.out.println("Hi");
		 }
	 }
}

Let us say, you want to specify a different object. You can do it as shown in the example below

public class HiThread{
	 void generate() {
		 Athlete athl = new Athlete();
		 //synchronized block
		 synchronized(athl) {
			 System.out.println("Hi");
			 athl.contest();
		 }
	 }
}

class Athlete{
	int stepLength=5;
	void contest() {
		 System.out.println("step length:,"+stepLength);
	}
}

synchronized Example

public class HiThread{
	int count=0;

	//synchronized method
	 synchronized void roll() {
	 	count++;
	 }

	 void generate() {

		 //synchronized block 1
		 synchronized(this) {
			 System.out.println("Hi");
		 }

		 Athlete athl = new Athlete();
		 //synchronized block 2
		 synchronized(athl) {
			 System.out.println("Hi");
			 athl.contest();
		 }
	 }
}

class Athlete{
	int stepLength=5;
	void contest() {
		 System.out.println("step length:,"+stepLength);
	}
}

<< final Keyword

volatile Keyword >>

















Searching using Binary Search Tree