{"id":7937,"date":"2021-01-20T16:23:21","date_gmt":"2021-01-20T10:53:21","guid":{"rendered":"https:\/\/www.h2kinfosys.com\/blog\/?p=7937"},"modified":"2025-12-18T05:41:10","modified_gmt":"2025-12-18T10:41:10","slug":"synchronization-in-java","status":"publish","type":"post","link":"https:\/\/www.h2kinfosys.com\/blog\/synchronization-in-java\/","title":{"rendered":"Synchronization in Java"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Introduction for synchronization in Java :<\/h3>\n\n\n\n<p>Synchronization in Java is a fundamental concept that ensures thread safety in multi-threaded programming. It allows developers to control the access of multiple threads to shared resources, preventing inconsistent behavior and data corruption. This blog dives into the details of synchronization in Java, its importance, and how to implement it effectively.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">What is Synchronization in Java?<\/h4>\n\n\n\n<p>In Java, synchronization is the capability to control the access of multiple threads to shared resources. It ensures that only one thread can access a synchronized block or method at a time, thus maintaining data integrity.<\/p>\n\n\n\n<p>Java\u2019s synchronization mechanism is built around the concept of monitors. Every object in Java has an intrinsic lock (or monitor lock) that is used for synchronization. When a thread enters a synchronized block or method, it acquires the lock associated with the object. Other threads attempting to access the same synchronized block or method must wait until the lock is released.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Best Practices for Using Synchronization in Java<\/h4>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Minimize Synchronized Blocks:<\/strong><br>Synchronize only the critical section of code to reduce contention and improve performance. This ensures that Synchronization in Java is used efficiently without unnecessarily blocking other threads.<\/li>\n\n\n\n<li><strong>Avoid Nested Locks:<\/strong><br>Nested synchronized blocks can lead to complex dependencies and increase the risk of deadlocks. Use structured locking mechanisms to simplify Synchronization in Java and avoid potential issues.<\/li>\n\n\n\n<li><strong>Use High-Level Utilities:<\/strong><br>Prefer high-level concurrency utilities from the <code>java.util.concurrent<\/code> package over low-level synchronization when possible. These utilities simplify the implementation and reduce errors in Synchronization in Java.<\/li>\n\n\n\n<li><strong>Document Synchronization Logic:<\/strong><br>Clearly document the purpose and scope of synchronization in your code. Properly documenting Synchronization in Java improves maintainability and helps other developers understand the logic.<\/li>\n\n\n\n<li><strong>Test Thoroughly:<\/strong><br>Multi-threaded code can be challenging to debug. Use robust testing strategies, including stress tests, to identify and resolve issues with Synchronization in Java early in the development process.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Thread Synchronization in Java<\/strong><\/h2>\n\n\n\n<p>Java provides built-in synchronization in Java mechanisms for managing access to shared resources. These include:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1. Synchronized Methods<\/strong><\/h3>\n\n\n\n<p>The <code>synchronized<\/code> a keyword can be applied to methods to restrict access to one thread at a time.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>java <code>public synchronized void synchronizedMethod() {\n    \/\/ Critical section\n}\n<\/code><\/code><\/pre>\n\n\n\n<p>When a thread invokes a synchronized method, it acquires the <strong>intrinsic lock (monitor lock)<\/strong> on the object. Other threads trying to access the synchronized method on the same object are blocked until the lock is released.<\/p>\n\n\n\n<p>In the<a class=\"rank-math-link\" href=\"https:\/\/www.h2kinfosys.com\/blog\/java-programming-masterclass-for-software-developers\/\"> Java platform<\/a>, synchronization in Java is the capability to control access to shared resources that can be shared between threads or processes. We will talk about thread synchronization because it&#8217;s a more common task. Threads can access the same fields and the object&#8217;s references. Without correct synchronization is can cause thread interference, memory consistency errors or unexpected behavior of your application.<\/p>\n\n\n\n<p>Let&#8217;s look at an example. It will help us to understand the problem without synchronization. Assuming that we have a user with a bank account. There are two transactions on that account with different duration. We are starting the longer transaction. Right after, we are calling the shorter one.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>public<\/strong> <strong>class<\/strong> SynchronizationExample {\n<strong>public<\/strong> <strong>static<\/strong> <strong>void<\/strong> main(String&#91;] args){\nAccount account = <strong>new<\/strong> Account();\nThread thread1 = <strong>new<\/strong> Transaction(account, 3000);\nThread thread2 = <strong>new<\/strong> Transaction(account, 1000);\nthread1.start();\nthread2.start();\n}\n}\n\n<strong>class<\/strong> Transaction <strong>extends<\/strong> Thread {\n<strong>private<\/strong> <strong>int<\/strong> timeToWait;\n<strong>private<\/strong> Account account;\n\n<strong>public<\/strong> Transaction(Account account,<strong>int<\/strong> timeToWait) {\n<strong>this<\/strong>.timeToWait = timeToWait;\n<strong>this<\/strong>.account = account;\n}\n\n<strong>public<\/strong> <strong>void<\/strong> run() {\n<strong>try<\/strong> {\naccount.performTransaction(timeToWait);\n} <strong>catch<\/strong> (InterruptedException e) {\ne.printStackTrace();\n}\n}\n}\n\n<strong>class<\/strong> Account {\n<strong>public<\/strong> <strong>void<\/strong> performTransaction(<strong>int<\/strong> timeToWait) <strong>throws<\/strong> InterruptedException {\nSystem.<strong><em>out<\/em><\/strong>.println(\"Before transaction \" + Thread.<em>currentThread<\/em>().getId());\nThread.<em>sleep<\/em>(timeToWait);\nSystem.<strong><em>out<\/em><\/strong>.println(\"After transaction \" + Thread.<em>currentThread<\/em>().getId());\n}\n}\n<\/code><\/pre>\n\n\n\n<p>The output of this application will be:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Before transaction 12\nBefore transaction 13\nAfter transaction 13\nAfter transaction 12<\/pre>\n\n\n\n<p>The output is inconsistent. The first transaction wasn&#8217;t finished, but the second already started. It can cause some problems for a bank client, who wants to know the real amount of money on his account after each transaction.&nbsp;<\/p>\n\n\n\n<p>Synchronization in Java is built on locks or monitors. A thread that needs consistent access has to acquire the lock before accessing them and release the lock when it&#8217;s done with them<\/p>\n\n\n\n<p>The Java platform allows us to do synchronization in different ways. It can be a synchronized method, synchronized block or static synchronization.&nbsp;<\/p>\n\n\n\n<p>We have to mention that constructor cannot be marked as synchronized. It will cause a syntax error because doesn&#8217;t have sense. Only the thread that creates that object should have access to its creation.Let&#8217;s mark our method performTransaction (<strong>int<\/strong> timeToWait) as synchronized. After this, our output will be:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Before transaction 12\nAfter transaction 12\nBefore transaction 13\nAfter transaction 13<\/pre>\n\n\n\n<p>This means that two transactions were done one after one. The first thread locked the method performTransaction (<strong>int<\/strong> timeToWait) until finished his work.&nbsp;<\/p>\n\n\n\n<p>Let&#8217;s use the synchronized block and get the same result:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>class<\/strong> Account {\n<strong>public<\/strong> <strong>void<\/strong> performTransaction(<strong>int<\/strong> timeToWait) <strong>throws<\/strong> InterruptedException {\n<strong>synchronized<\/strong> (<strong>this<\/strong>) {\nSystem.<strong><em>out<\/em><\/strong>.println(\"Before transaction \" + &nbsp; &nbsp; Thread.<em>currentThread<\/em>().getId());\nThread.<em>sleep<\/em>(timeToWait);\nSystem.<strong><em>out<\/em><\/strong>.println(\"After transaction \" + Thread.<em>currentThread<\/em>().getId());\n}\n}\n}\n<\/code><\/pre>\n\n\n\n<p>Here we specified the object for synchronized statements. That object provides the intrinsic lock. The scope of the synchronized block is usually smaller than the synchronized method scope. We are blocking the whole object. It is better sometimes to synchronize only a part of your method.<\/p>\n\n\n\n<p>Let&#8217;s look at a bit different example. We have a value that will be changed by two threads. The example of code without synchronization between threads:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>public<\/strong> <strong>class<\/strong> SynchronizationExample {\n<strong>public<\/strong> <strong>static<\/strong> <strong>void<\/strong> main(String&#91;] args) <strong>throws<\/strong> InterruptedException {\nClientAccount account = <strong>new<\/strong> ClientAccount();\nSystem.<strong><em>out<\/em><\/strong>.println(\"Account balance before all transactions is \" + &nbsp; &nbsp; account.getBalance());\n\/\/transaction to send 100 to account\nThread thread1 = <strong>new<\/strong> Transaction(account,100,3000);\n\/\/transaction to get 50 from account\nThread thread2 = <strong>new<\/strong> Transaction(account,-50,1000);\n\nthread1.start();\nthread2.start();\n}\n}\n\n<strong>class<\/strong> Transaction <strong>extends<\/strong> Thread {\n<strong>private<\/strong> <strong>int<\/strong> timeToWait;\n<strong>private<\/strong> <strong>int<\/strong> value;\n<strong>private<\/strong> ClientAccount account;\n\n<strong>public<\/strong> Transaction(ClientAccount account, <strong>int<\/strong> value, <strong>int<\/strong> timeToWait) {\n<strong>this<\/strong>.timeToWait = timeToWait;\n<strong>this<\/strong>.value = value;\n<strong>this<\/strong>.account = account;\n}\n\n<strong>public<\/strong> <strong>void<\/strong> run() {\n<strong>try<\/strong> {\naccount.changeBalance(value, timeToWait);\n} <strong>catch<\/strong> (InterruptedException e) {\ne.printStackTrace();\n}\n}\n}\n\n<strong>class<\/strong> ClientAccount {\n<strong>private<\/strong> <strong>Integer<\/strong> balance = 0;\n<strong>public<\/strong> <strong>void<\/strong> changeBalance(<strong>int<\/strong> value, <strong>int<\/strong> time) <strong>throws<\/strong> InterruptedException {\nbalance += value;\nThread.<em>sleep<\/em>(time);\nSystem.<strong><em>out<\/em><\/strong>.println(\"Account balance after \" + value + \" is \" + balance);\n}\n<strong>public<\/strong> <strong>int<\/strong> getBalance() {\n<strong>return<\/strong> balance;\n}\n}\n<\/code><\/pre>\n\n\n\n<p>The output will be:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Account balance before all transactions is 0\nAccount balance after -50 is 50\nAccount balance after 100 is 50<\/pre>\n\n\n\n<p>Our client had a balance 0. We started two transactions. The first was to transfer to the client account 100. The second was to transfer from account 50.&nbsp; The application result looks not logical:&nbsp;<\/p>\n\n\n\n<p>0-50 = 50;&nbsp;<\/p>\n\n\n\n<p>50+100 = 50;<\/p>\n\n\n\n<p>The reason is simple. The two treads entered the method changeBalance(<strong>int<\/strong> value, <strong>int<\/strong> time). The first thread takes more time. That is why the second one raced it. Finally, we got the messy output.<\/p>\n\n\n\n<p>We can to synchronize access of our treads to the balance value. Let&#8217;s use the synchronized block for this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>class<\/strong> ClientAccount {\n<strong>private<\/strong> Integer balance = 0;\n\n<strong>public<\/strong> <strong>void<\/strong> changeBalance(<strong>int<\/strong> value, <strong>int<\/strong> time) <strong>throws<\/strong> InterruptedException {\n<strong>synchronized<\/strong> (balance) {\nbalance += value;\nThread.<em>sleep<\/em>(time);\nSystem.<strong><em>out<\/em><\/strong>.println(\"Account balance after \" + value + \" is \" + &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; balance);\n}\n}\n...\n}\n<\/code><\/pre>\n\n\n\n<p>Now, our output is consistent and understandable:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Account balance before all transactions is 0\nAccount balance after 100 is 100\nAccount balance after -50 is 50<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">The syntax of the synchronized block is:\nsynchronized (object reference expression) {&nbsp;&nbsp;&nbsp;\n&nbsp;&nbsp;\/\/code block&nbsp;&nbsp;&nbsp;\n}\n<\/pre>\n\n\n\n<p>It is important to note that object reference expression has to be an Object, we cannot use primitive types. That is why we used the object wrapper for int in our example. You will get a java.lang.NullPointerException, in case object reference expression of a synchronized block is null.<\/p>\n\n\n\n<p>We can create a synchronized class. In this case, all methods of this class will be declared as synchronization in Java . For example, Vector, Stack, Hashtable, StringBuffer. They are not recommended for use. The reason is that they are slow.<\/p>\n\n\n\n<p>Static synchronization is when you use synchronization for a static method. In this case, the all-class will be locked, not just object.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>public<\/strong> <strong>class<\/strong> StaticSynchExample {\n<strong>public<\/strong> <strong>static<\/strong> <strong>void<\/strong> main(String&#91;] args){\nThread thread1 = <strong>new<\/strong> Printer(1);\nThread thread2 = <strong>new<\/strong> Printer(2);\nthread1.start();\nthread2.start();\n}\n}\n\n<strong>class<\/strong> Printer <strong>extends<\/strong> Thread {\n<strong>private<\/strong> <strong>int<\/strong> k;\n<strong>public<\/strong> Printer(<strong>int<\/strong> k) {\n<strong>this<\/strong>.k = k;\n}\n<strong>public<\/strong> <strong>void<\/strong> run() {\n<strong>try<\/strong> {\nDocument.<em>print<\/em>(k);\n} <strong>catch<\/strong> (InterruptedException e) {\ne.printStackTrace();\n}\n}\n}\n\n<strong>class<\/strong> Document {\n<strong>private<\/strong> <strong>static<\/strong> <strong>int<\/strong> <em>K<\/em> = 1;\n<strong>public<\/strong> <strong>static<\/strong> <strong>synchronized<\/strong> <strong>void<\/strong> print(<strong>int<\/strong> k) <strong>throws<\/strong> InterruptedException {\n<em>K<\/em> = k;\nSystem.<strong><em>out<\/em><\/strong>.print(\"Start\");\n<strong>for<\/strong>(<strong>int<\/strong> i = 0; i &lt; 5; i++) {\nSystem.<strong><em>out<\/em><\/strong>.print(i*<em>K<\/em> + \" \");\n}\nSystem.<strong><em>out<\/em><\/strong>.println(\"End\");\n}\n}\n<\/code><\/pre>\n\n\n\n<p>The output will be not logical. The threads accessed and changed our coefficient randomly:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Start Start 0 0 2 4 6 8 End\n2 4 6 8 End\n<\/pre>\n\n\n\n<p>After marking our print(int k) method as synchronized, we will get consistent result:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Start 0 1 2 3 4 End\nStart 0 2 4 6 8 End<\/pre>\n\n\n\n<p>Let&#8217;s summarize the important things to know about the synchronized keyword. Synchronization guarantees that two threads cannot execute a synchronized method with the same lock simultaneously or concurrently. The synchronized keyword can be used for methods or blocks (synchronized statements). When a thread enters a synchronized part of code, the code acquires a lock. This lock exists until the thread leaves that code or an error\/exception occurs.<\/p>\n\n\n\n<p>A thread acquires an object level lock when enters an instance synchronized method. A thread acquires a class level lock when enters a static synchronized method.&nbsp;<\/p>\n\n\n\n<p>The synchronized keyword is re-entrant. Let&#8217;s explain it. A thread that holds a lock on one synchronized method does not need to acquire a lock for a synchronized method called from the first method.<\/p>\n\n\n\n<p>There is one main disadvantage of Java synchronized keyword. It doesn&#8217;t allow concurrent read. This limits scalability. You can use ReentrantReadWriteLock for this use case. It is from package java.util.concurrent.locks. It provides a ready implementation of the ReadWriteLock in Java.<\/p>\n\n\n\n<p>The synchronized keyword can control access to a shared object just within the same JVM.<\/p>\n\n\n\n<p>A synchronized method in Java is very slow. They degrade performance. So, it better to use blocks for critical sections of code.<\/p>\n\n\n\n<p>Your synchronized code could cause a <a href=\"https:\/\/www.h2kinfosys.com\/blog\/deadlock-in-java-with-examples\/\" class=\"rank-math-link\">java deadlock<\/a> or starvation while accessing by multiple threads if synchronization is not implemented correctly.<\/p>\n\n\n\n<p>It&#8217;s not good to use a non-final field or String on the synchronized block. A string is an immutable object. A literal string and interned string gets stored in the String pool. Another thread can be locked on the same object despite being completely unrelated. It can cause unexpected behavior.<\/p>\n\n\n\n<p>Besides the synchronized keyword,&nbsp; we can also use explicit locks. The Java language includes the Lock interface since version 1.5. There are different implementations of this interface (ReentrantLock, ReadWriteLock, <a href=\"https:\/\/stackoverflow.com\/questions\/26094200\/what-is-stampedlock-in-java\" data-type=\"link\" data-id=\"https:\/\/stackoverflow.com\/questions\/26094200\/what-is-stampedlock-in-java\" rel=\"nofollow noopener\" target=\"_blank\">StampedLock<\/a>, etc ). Let&#8217;s take a look at the simplest ReentrantLock, just to replace our synchronized keyword from our first example. We will replace this part:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>class<\/strong> Account {\n<strong>public<\/strong> <strong>void<\/strong> performTransaction(<strong>int<\/strong> timeToWait) <strong>throws<\/strong> InterruptedException {\n<strong>synchronized<\/strong> (<strong>this<\/strong>) {\nSystem.<strong><em>out<\/em><\/strong>.println(\"Before transaction \" + &nbsp; &nbsp; Thread.<em>currentThread<\/em>().getId());\nThread.<em>sleep<\/em>(timeToWait);\nSystem.<strong><em>out<\/em><\/strong>.println(\"After transaction \" + Thread.<em>currentThread<\/em>().getId());\n}\n}\n}\n\nThis code work the same as:\n\n<strong>class<\/strong> Account {\n<strong>private<\/strong> ReentrantLock lock = <strong>new<\/strong> ReentrantLock();\n<strong>public<\/strong> <strong>void<\/strong> performTransaction(<strong>int<\/strong> timeToWait) <strong>throws<\/strong> InterruptedException {\nlock.lock();\nSystem.<strong><em>out<\/em><\/strong>.println(\"Before transaction \" + &nbsp; Thread.<em>currentThread<\/em>().getId());\nThread.<em>sleep<\/em>(timeToWait);\nSystem.<strong><em>out<\/em><\/strong>.println(\"After transaction \" + Thread.<em>currentThread<\/em>().getId());\nlock.unlock();\n}\n}\n<\/code><\/pre>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction for synchronization in Java : Synchronization in Java is a fundamental concept that ensures thread safety in multi-threaded programming. It allows developers to control the access of multiple threads to shared resources, preventing inconsistent behavior and data corruption. This blog dives into the details of synchronization in Java, its importance, and how to implement [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":7941,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[42],"tags":[],"class_list":["post-7937","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java-tutorials"],"_links":{"self":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/7937","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/comments?post=7937"}],"version-history":[{"count":2,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/7937\/revisions"}],"predecessor-version":[{"id":33087,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/posts\/7937\/revisions\/33087"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media\/7941"}],"wp:attachment":[{"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/media?parent=7937"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/categories?post=7937"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.h2kinfosys.com\/blog\/wp-json\/wp\/v2\/tags?post=7937"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}