Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Block Synchronization in Java

  • In Java, synchronized blocks are used for synchronizing specific parts of a method's code. This technique ensures that only one thread can access the synchronized block at a time, allowing for safe and orderly execution of critical code.
    • Imagine you have a method with 100 lines of code, but you only need to synchronize 5 of them. In such cases, synchronized blocks come to the rescue. Instead of synchronizing the entire method, you can isolate the critical 5 lines within a synchronized block.
    • By enclosing these lines within a synchronized block, you achieve the same effect as if the entire method was synchronized. This means that only one thread can execute the synchronized block at any given time, preventing any potential conflicts or data corruption.
    • By strategically using synchronized blocks, you can improve the performance of your code by minimizing unnecessary synchronization and focusing only on the critical sections.
    • Optimizing code synchronization in Java using synchronized blocks not only ensures the correct execution of shared resources but also enhances the overall efficiency and responsiveness of your application.

Block Synchronization


Syntax :

synchronized (object reference expression) {     
    //code inside synchronized block     
}




class SyncTable{  
    void printTable(int temp){
	  synchronized(this) {
	   for(int i=1;i<=5;i++){  
		   System.out.println(Thread.currentThread().getName() + ": " +temp + "*"+ i + " value: " + i*temp); 
		 try{  
	      Thread.sleep(400);  
	     }
	     catch(Exception e){
	    	 System.out.println(e);
	     }  
	   }
	 }
  }  
}  
  
class MyThread1 extends Thread{  
	SyncTable synctable;  
	MyThread1(SyncTable synctable){  
	 this.synctable=synctable;  
	}  
	public void run(){  
		synctable.printTable(5);  
	}  
  
}  
class MyThread2 extends Thread{  
	SyncTable synctable;  
	MyThread2(SyncTable synctable){  
	 this.synctable=synctable;  
	}  
	public void run(){  
		synctable.printTable(9);  
	}  
}

public class Main{
    public static void main(String arg[]){
    	SyncTable synctable = new SyncTable(); //only one object  
    	MyThread1 thread1=new MyThread1(synctable);  
    	MyThread2 thread2=new MyThread2(synctable);  
    	thread1.start();  
    	thread2.start();  
    }
}





Output:

Thread-1: 9*1 value: 9
Thread-1: 9*2 value: 18
Thread-1: 9*3 value: 27
Thread-1: 9*4 value: 36
Thread-1: 9*5 value: 45
Thread-0: 5*1 value: 5
Thread-0: 5*2 value: 10
Thread-0: 5*3 value: 15
Thread-0: 5*4 value: 20
Thread-0: 5*5 value: 25 

Important points to remember

  • In Java, when a thread enters a synchronized method or block, it acquires a lock. This lock is released when the thread completes its task and exits the synchronized method. The use of locks ensures mutual exclusion, allowing only one thread to access the synchronized section at a time.
    • It is important to understand the distinction between synchronized instance methods and synchronized static methods. When a thread enters a synchronized instance method or block, it obtains an object-level lock. This means that other threads will be blocked from accessing other synchronized instance methods of the same object until the current thread releases the lock. On the other hand, when a thread enters a synchronized static method or block, it obtains a class-level lock. This means that other threads will be blocked from accessing any synchronized static methods of the class until the current thread releases the lock.
    • In Java, wait(), notify(), and notifyAll() are essential synchronization methods. These methods are used for inter-thread communication and coordination. The wait() method causes a thread to temporarily release the lock and enter a waiting state until it is notified by another thread. The notify() method wakes up a single waiting thread, while the notifyAll() method wakes up all the waiting threads. These methods play a crucial role in managing the execution flow and synchronization of threads in Java.
    • One important thing to note is that the java synchronized keyword cannot be used with variables. The synchronization mechanism in Java is based on locks associated with objects or classes, rather than variables. Therefore, it is not possible to synchronize on individual variables.
    • When using synchronized blocks, it is recommended to avoid synchronizing on non-final fields. This is because the reference to a non-final field can change at any time, leading to different threads synchronizing on different objects. Consequently, there will be no synchronization at all, defeating the purpose of using synchronized blocks. To ensure consistent synchronization, it is advisable to synchronize on final fields or dedicated lock objects.



Advantages block synchronization in java

  • Multithreading : In a multithreaded environment, synchronization is a crucial technique for achieving mutual exclusion on shared resources. By using block synchronization, we can ensure that only one thread can access a synchronized section of code at a time. This prevents race conditions and data inconsistencies that can occur when multiple threads concurrently modify shared resources.
  • Instance and Static Methods : Block synchronization in Java is compatible with both instance methods and static methods. Synchronized instance methods and synchronized static methods can be used concurrently because they lock different objects. This enables precise synchronisation control based on the unique requirements of the programme.

Limitations block synchronization in java

  • Concurrency Limitations : One limitation of Java synchronization is that it does not support concurrent reads. When multiple threads only need to read a shared resource and not modify it, synchronization can become a bottleneck. In such cases, alternative synchronization mechanisms like ReadWriteLock or atomic variables should be considered to improve performance.
  • Decreases Efficiency : Java synchronized methods tend to run slower compared to unsynchronized methods. This is because synchronized methods acquire and release locks, which involves additional overhead. As a result, excessive use of synchronization can lead to decreased efficiency and negatively impact performance. It is essential to synchronize methods and blocks only when necessary to avoid unnecessary performance penalties.
Static Synchronization in Java Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java

Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.