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

Synchronization in Java

  • You can ensure that only one thread at a time can access a shared resource by using Java synchronisation feature. This helps prevent conflicts when multiple threads try to change the same resource simultaneously.
    • The "synchronised" keyword in Java allows for synchronisation. By marking a method or block of code as synchronized, only one thread can access it at any given time. When a thread enters a synchronized block or method, it gains exclusive control over the object or class associated with it. If another thread tries to enter the same block or method, it will be stopped until the first thread finishes and releases the control.
Table Of Content

  • Synchronization in Java
  • Thread Synchronization
  • Inter Thread Communication in java
  • Lock Concept in Java
  • Issue without Synchronization
  • Java Synchronized Method






Types of Synchronization

There are two types of synchronization

  • Process Synchronization
  • Thread Synchronization

Process Synchronization

  • A process is nothing more than an active program. It runs in a separate process that is not linked to any other. Memory and CPU time are allocated to the process by the operating system. Process synchronization is the sharing of capabilities between two or more processes while ensuring data consistency. In a programming language, a Critical Section is a piece of code that is shared by multiple processes. There are several methods for preventing critical section problems, including Peterson's Solution, but the most well-known is Semaphores.

Thread Synchronization

  • Thread synchronization refers to the coordinated execution of a vital resource by multiple threads. A thread is a distinct subroutine that can operate within a single process.
  • A single process can have multiple threads, and the program can schedule all of them to use the same resource. In reality, a single thread contains multiple threads.
  • There are two types of thread synchronization :
    • Mutual Exclusive
      • Synchronized method.
      • Synchronized block.
      • Static synchronization.
    • Collaboration (Inter Thread Communication in java)




Mutual Exclusive

  • Mutual exclusion, also referred to as "mutex," is a Java. Mutual exclusion (mutex) is a way to control access to a resource in Java. It ensures that only one thread can use the resource at a time, preventing conflicts and ensuring orderly execution. This is required to avoid race conditions, which occur when multiple threads attempt to access the same resource at the same time, resulting in unpredictable results.
    • synchronized keyword : The synchronized keyword is used to show that a specific section of code is crucial and can only be accessed by one thread at a time. When a thread enters a synchronized block, it gains control over the object's lock. Other threads that try to enter the block are halted until the first thread releases the lock. This guarantees proper thread synchronisation and the thread-safe execution of the synchronised code, preventing conflicts.
    • Lock interface : The Lock interface is more advanced than the synchronized keyword in terms of locking options. It enables you to create finer-grained locks, such as read-write locks, which allow multiple threads to read a shared resource at the same time but only one thread to write to it.
    • ReentrantLock : The ReentrantLock class implements the Lock interface and adds features such as the ability to interrupt a thread that is waiting for a lock.
    • Atomic Variables : Atomic Variables, such as AtomicInteger, AtomicLong, and AtomicBoolean, are special variables that can be updated atomically, ensuring that they are correctly accessed and updated by multiple threads.
    • StampedLock : This class provides similar functionality to ReentrantLock but also allows for more fine-grained access to shared data. It operates in three modes: write lock, optimistic read, and read lock.

Collaboration (Inter Thread Communication in java)

  • In Java, inter-thread communication can be achieved using several methods, including :
    • wait() and notify() methods : These methods are used for synchronized inter-thread communication. The wait() method makes the current thread wait until another thread calls the notify() or notifyAll() methods on the same object.



    • join() method :The join() method allows one thread to wait for another thread to finish.
    • Executor framework : Threads can be managed and executed using the Executor framework. It makes it simple to run tasks concurrently.
    • Future and Callable :The Future and Callable interfaces allow a thread to return a value after its execution is complete.
    • BlockingQueue : When you try to take an element from a BlockingQueue and the queue is empty, or when you try to put an element in it and the queue is already full, the queue will block.
    • Semaphore : A Semaphore is a synchronization mechanism that can be used to control multiple threads' access to a shared resource.
    • Atomic Variables : Atomic Variables, such as AtomicInteger, AtomicLong, and AtomicBoolean, are special variables that can be updated atomically, ensuring that they are correctly accessed and updated by multiple threads.

Lock Concept in Java

  • In Java, the Lock Concept synchronizes. The synchronized keyword in the Java programming language was used to create the Synchronization Mechanism. It is built on top of the locking mechanism, which the Java Virtual Machine manages (JVM). In Java, the keyword synchronize can only be used on methods and blocks; it cannot be used on classes or variables. In Java, the synchronized keyword generates a critical section, which is a block of code. To gain access to the critical region, the thread must first obtain a lock on the relevant object.
  • Locks, like synchronized blocks, are a thread synchronization mechanism; however, locks can be more complicated than synchronized blocks in Java. Locks (and other more complex synchronization methods) are built with synchronized blocks, so we can't completely eliminate the synchronizing in java keyword.
  • Since Java 5, the package java.util.concurrent.locks has included a number of lock implementations.

Issue without Synchronization


class SyncTable{  
	void printTable(int temp){ //method not synchronized  
	   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-0: 5*1 value: 5
Thread-1: 9*2 value: 18
Thread-0: 5*2 value: 10
Thread-1: 9*3 value: 27
Thread-0: 5*3 value: 15
Thread-1: 9*4 value: 36
Thread-0: 5*4 value: 20
Thread-1: 9*5 value: 45
Thread-0: 5*5 value: 25
 


Java Synchronized Method


Any method that is declared as synchronized is referred to as a synchronized method. To lock an object for any shared resource, use the synchronized method.When a thread calls a synchronized method, the lock for that object is automatically acquired and released when the thread completes its task.


class SyncTable{  
	synchronized void printTable(int temp){ //method not synchronized  
	   for(int i=1;i<=5;i++){  
		   System.out.println(Thread.currentThread().getName() + ":- " +i + "*"+ 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-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
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 

Synchronized block 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.