{"id":78942,"date":"2020-06-09T09:00:15","date_gmt":"2020-06-09T03:30:15","guid":{"rendered":"https:\/\/techvidvan.com\/tutorials\/?p=78942"},"modified":"2020-06-09T09:00:15","modified_gmt":"2020-06-09T03:30:15","slug":"synchronized-in-java","status":"publish","type":"post","link":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/","title":{"rendered":"Synchronized in Java Syntax and Example"},"content":{"rendered":"<p>While working in a multi-threaded environment, there are some situations when multiple threads in a single program try to access the same resource at the same time.<\/p>\n<p>This situation of concurrency issues may result in unexpected and erroneous results.<\/p>\n<p>For example, there is a file, and two or more threads are trying to write the data in the same file at the same time. This concurrent situation may lead to a condition where one thread is trying to open the file while another thread is trying to close it.<\/p>\n<p>In this case, neither thread can operate on the file. And, if the thread has access to the file, it can override the data that is already written by another thread, this may eventually corrupt the data.<\/p>\n<p>To overcome this situation, we need to make sure that at a time only a single thread can access the resource at a given point of time.<\/p>\n<p>For this, Java provides a mechanism of synchronization that helps to avoid such race conditions by providing synchronized thread access to the shared resource or data.<\/p>\n<p>In this article, we will study the synchronized keyword in Java that helps us to implement the synchronization in Java.<\/p>\n<p>We will also learn how to use the <strong>synchronized<\/strong> keyword in Java with examples and many more things about this keyword.<\/p>\n<h3>Synchronized keyword in Java<\/h3>\n<p>As Java is a multi-threaded language, it supports a very important concept of Synchronization.<\/p>\n<p>The process of allowing only a single thread to access the shared data or resource at a particular point of time is known as <strong>Synchronization<\/strong>.<\/p>\n<p>This helps us to protect the data from the access by multiple threads. Java provides the mechanism of synchronization using the synchronized blocks.<\/p>\n<p>We declare all synchronized blocks in Java are using a synchronized keyword. A block that is declared with a synchronized keyword ensures that only a single thread executes at a particular time.<\/p>\n<p>No other thread can enter into that synchronized block until the thread inside that block completes its execution and exits the block.<\/p>\n<p>We can use the synchronized keyword to mark four different types of blocks:<\/p>\n<p><a href=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/Methods-of-Synchronization-in-Java.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-79034\" src=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/sites\/2\/2020\/06\/Methods-of-Synchronization-in-Java.jpg\" alt=\"Synchronization methods in Java\" width=\"654\" height=\"531\" \/><\/a><\/p>\n<h3>Syntax of using synchronized block in Java<\/h3>\n<p>The following is the general syntax for writing a synchronized block. Here <strong>lockObject<\/strong> is a reference to an object whose lock is related to the synchronized statements.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">synchronized( lockObject )\n{\n\/\/ synchronized statements\n\n}\n<\/pre>\n<h3>Types of Synchronization in Java<\/h3>\n<p>There are two types of synchronization in Java. They are:<\/p>\n<p><strong>1.<\/strong> Process Synchronization<br \/>\n<strong>2.<\/strong> Thread Synchronization<\/p>\n<h4>1. Process Synchronization<\/h4>\n<p>Process Synchronization is the term used to define Sharing the resources between two or more processes and meanwhile ensuring the inconsistency of data.<\/p>\n<p>In a programming language, the piece of code that is being shared by different processes is called the Critical Section.<\/p>\n<p>There are many solutions to avoid critical section problem like Peterson\u2019s Solution, the most popular way to deal with this is Semaphores.<\/p>\n<h4>2. Thread Synchronization<\/h4>\n<p>The concurrent execution of the critical resource by two or more Threads is termed as Thread Synchronization. Thread is the subroutine that can execute independently within a single process.<\/p>\n<p>A single process can contain multiple threads and the process can schedule all the threads for a critical resource. In fact, a single thread also contains multiple threads.<\/p>\n<h3>Example of Synchronized in Java<\/h3>\n<h4>1. Synchronized Instance methods<\/h4>\n<p>When we use a synchronized block with the instance methods, then each object has its synchronized method.<\/p>\n<p>There can be only one thread for each object, that can execute inside a method. If there is more than one object, then only a single thread can execute inside the block for each object.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class MyCounter {\n  private int count = 0;\n  public synchronized void increment(int value) {\n    this.count += value;\n  }\n  public synchronized void decrement(int value) {\n    this.count -= value;\n  }\n}<\/pre>\n<h4>2. Synchronized Static Methods<\/h4>\n<p>We can mark the Static methods as synchronized just like we mark the instance methods using the synchronized keyword. Below is an example of a Java synchronized static method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public static MyStaticCounter {\n  private static int count = 0;\n  public static synchronized void increment(int value) {\n    count += value;\n  }\n}<\/pre>\n<h4>3. Synchronized block inside Instance Methods<\/h4>\n<p>If you do not want to synchronize the whole method, you can just make a particular block inside the method as synchronized.<\/p>\n<p>Below is the example of a synchronized block of Java code inside an unsynchronized Java method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public void increment(int value) {\n  synchronized(this) {\n    this.count += value;\n  }\n}<\/pre>\n<h4>4. The synchronized block inside Static Methods<\/h4>\n<p>We can also use the Synchronized blocks inside the static methods. Below is the example of using a synchronized block inside the static method:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class MyClass {\n  public static void print(String message) {\n    synchronized(MyClass.class) {\n      log.writeln(message);\n    }\n  }\n}<\/pre>\n<h3>Example of Java synchronized in Multithreading<\/h3>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">package com.techvidvan.constructorchaining;\n\/\/ A Class used to send a message \nclass Sender \n{ \n  public void sendMessage(String message)\n  { \n    System.out.println(\"\\nSending \"  + message);\n    try\n    { \n      Thread.sleep(1000); \n    } \n    catch (Exception e) \n    { \n      System.out.println(\"Thread interrupted.\"); \n    } \n    System.out.println(\"\\n\" +message+ \"Sent\");\n  }\n} \n\/\/ Class for sending a message using Threads \nclass SendUsingThreads extends Thread \n{ \n  private String message; \n  Sender sender; \n\n  \/\/ Receives a message object and a string message to be sent \n  SendUsingThreads(String msg, Sender object)\n  { \n    message = msg;\n    sender = object; \n  } \n\n  public void run() \n  { \n    \/\/ This will ensure that only one thread sends a message at a time. \n    synchronized(sender) \n    { \n      \/\/ synchronizing the send object \n      sender.sendMessage(message);\n    } \n  } \n} \n\/\/ Driver class \npublic class Demo\n{ \n  public static void main(String args[]) \n  { \n    Sender sender = new Sender(); \n    SendUsingThreads sender1 = new SendUsingThreads( \"Hello \" , sender);\nSendUsingThreads sender2 =  new SendUsingThreads( \"Welcome to TechVidvan Tutorials \", sender);\n\n    \/\/ Start two threads of SendUsingThreads type \n    sender1.start(); \n    sender2.start(); \n\n    \/\/ wait for threads to end \n    try\n    { \n      sender1.join(); \n      sender2.join(); \n    } \n    catch(Exception e) \n    { \n      System.out.println(\"Interrupted\"); \n    } \n  } \n} \n<\/pre>\n<p><strong>Output:<\/strong><br \/>\nSending Hello<\/p>\n<p>Hello Sent<\/p>\n<p>Sending Welcome to TechVidvan Tutorials<\/p>\n<p>Welcome to TechVidvan Tutorials Sent<\/p>\n<h3>Need for synchronized in Java<\/h3>\n<p>We use the Java synchronized keyword as it helps in performing various activities related to concurrent programming. Some of the essential features of the synchronized keyword are:<\/p>\n<p><strong>1.<\/strong> The synchronized keyword in Java provides the facility of locking, which ensures that no race condition occurs among threads.<\/p>\n<p><strong>2.<\/strong> The synchronized keyword also prevents the reordering of the program statements.<\/p>\n<p><strong>3.<\/strong> The synchronized keyword provides locking and unlocking. The thread needs to get the lock before getting inside the synchronized block. After getting the lock, it reads data from the main memory.<\/p>\n<p>After reading the data, it flushes the write operation and then releases the lock.<\/p>\n<h3>Important points of synchronized keyword in Java<\/h3>\n<p><strong>1.<\/strong> Synchronized keyword in Java ensures that <strong>only a single thread can access shared data at a time<\/strong>.<\/p>\n<p><strong>2.<\/strong> Using Java synchronized keyword, we can only make a <strong>block or a method<\/strong> as synchronized.<\/p>\n<p><strong>3.<\/strong> A thread <strong>acquires a lock<\/strong> when it gets inside a synchronized block. And, after leaving that method, the thread <strong>releases that lock. <\/strong><\/p>\n<p><strong>4.<\/strong> If we try to use a null object in the synchronized block then we may get a NullPointerException<strong>. <\/strong><\/p>\n<p><strong>5.<\/strong> Using the Java synchronized keyword, we cannot use <strong>more than one JVM<\/strong> to provide access control to a shared resource.<\/p>\n<p><strong>6.<\/strong> The <strong>performance<\/strong> of the system can degrade due to the slow working of the synchronized keyword.<\/p>\n<p><strong>7.<\/strong> We should prefer to use the <strong>Java synchronized block rather than the Java synchronized method<\/strong>.<\/p>\n<p><strong>8.<\/strong> If we do not implement the synchronization properly in our code, then this might result in <strong>deadlock or starvation<\/strong>.<\/p>\n<p><strong>9.<\/strong> It is illegal to use a <strong>synchronized keyword with the constructor<\/strong> in Java. Also, you can not use the synchronized keyword with the <strong>variables in Java<\/strong>.<\/p>\n<p><strong>10.<\/strong> There are some important methods defined in the Object class that we can use while implementing synchronization in Java that are <strong>wait(), notify(), and notifyAll()<\/strong>.<\/p>\n<h3>Conclusion<\/h3>\n<p>In this Java article, we discussed different ways of using the synchronized keyword to achieve synchronization. We can either use it with methods or we can use it inside the block of a method.<\/p>\n<p>We studied the need for using synchronization in Java. Then we finally covered each way of using a synchronized keyword with the help of an example for your better understanding.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>While working in a multi-threaded environment, there are some situations when multiple threads in a single program try to access the same resource at the same time. This situation of concurrency issues may result&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":79033,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[183],"tags":[2793,2794,2795,2796,2797],"class_list":["post-78942","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-java","tag-java-synchronized","tag-java-synchronized-block","tag-java-synchronized-method","tag-synchronized-in-java","tag-what-is-java-synchronized-method"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.7 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Synchronized in Java Syntax and Example - TechVidvan<\/title>\n<meta name=\"description\" content=\"What is synchronized in java - Synchronized keyword in Java with need, syntax and example in multithreading, Types of Synchronization - Process, Thread\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Synchronized in Java Syntax and Example - TechVidvan\" \/>\n<meta property=\"og:description\" content=\"What is synchronized in java - Synchronized keyword in Java with need, syntax and example in multithreading, Types of Synchronization - Process, Thread\" \/>\n<meta property=\"og:url\" content=\"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/\" \/>\n<meta property=\"og:site_name\" content=\"TechVidvan\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/TechVidvan\/\" \/>\n<meta property=\"article:published_time\" content=\"2020-06-09T03:30:15+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Synchronized-Keyword-in-Java.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"802\" \/>\n\t<meta property=\"og:image:height\" content=\"420\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"TechVidvan Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:site\" content=\"@vidvantech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"TechVidvan Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"7 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Synchronized in Java Syntax and Example - TechVidvan","description":"What is synchronized in java - Synchronized keyword in Java with need, syntax and example in multithreading, Types of Synchronization - Process, Thread","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/","og_locale":"en_US","og_type":"article","og_title":"Synchronized in Java Syntax and Example - TechVidvan","og_description":"What is synchronized in java - Synchronized keyword in Java with need, syntax and example in multithreading, Types of Synchronization - Process, Thread","og_url":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/","og_site_name":"TechVidvan","article_publisher":"https:\/\/www.facebook.com\/TechVidvan\/","article_published_time":"2020-06-09T03:30:15+00:00","og_image":[{"width":802,"height":420,"url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Synchronized-Keyword-in-Java.jpg","type":"image\/jpeg"}],"author":"TechVidvan Team","twitter_card":"summary_large_image","twitter_creator":"@vidvantech","twitter_site":"@vidvantech","twitter_misc":{"Written by":"TechVidvan Team","Est. reading time":"7 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/#article","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/"},"author":{"name":"TechVidvan Team","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22"},"headline":"Synchronized in Java Syntax and Example","datePublished":"2020-06-09T03:30:15+00:00","mainEntityOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/"},"wordCount":1097,"commentCount":0,"publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Synchronized-Keyword-in-Java.jpg","keywords":["Java Synchronized","Java Synchronized block","Java Synchronized method","Synchronized in Java","What is Java Synchronized Method"],"articleSection":["Java Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/","url":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/","name":"Synchronized in Java Syntax and Example - TechVidvan","isPartOf":{"@id":"https:\/\/techvidvan.com\/tutorials\/#website"},"primaryImageOfPage":{"@id":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/#primaryimage"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/#primaryimage"},"thumbnailUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Synchronized-Keyword-in-Java.jpg","datePublished":"2020-06-09T03:30:15+00:00","description":"What is synchronized in java - Synchronized keyword in Java with need, syntax and example in multithreading, Types of Synchronization - Process, Thread","breadcrumb":{"@id":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/#primaryimage","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Synchronized-Keyword-in-Java.jpg","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2020\/06\/Synchronized-Keyword-in-Java.jpg","width":802,"height":420,"caption":"Synchronized in Java"},{"@type":"BreadcrumbList","@id":"https:\/\/techvidvan.com\/tutorials\/synchronized-in-java\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/techvidvan.com\/tutorials\/"},{"@type":"ListItem","position":2,"name":"Synchronized in Java Syntax and Example"}]},{"@type":"WebSite","@id":"https:\/\/techvidvan.com\/tutorials\/#website","url":"https:\/\/techvidvan.com\/tutorials\/","name":"TechVidvan Blogs","description":"","publisher":{"@id":"https:\/\/techvidvan.com\/tutorials\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/techvidvan.com\/tutorials\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/techvidvan.com\/tutorials\/#organization","name":"TechVidvan","url":"https:\/\/techvidvan.com\/tutorials\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/","url":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","contentUrl":"https:\/\/techvidvan.com\/tutorials\/wp-content\/uploads\/2024\/03\/techvidvan-logo-200x50-1.webp","width":200,"height":50,"caption":"TechVidvan"},"image":{"@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/TechVidvan\/","https:\/\/x.com\/vidvantech"]},{"@type":"Person","@id":"https:\/\/techvidvan.com\/tutorials\/#\/schema\/person\/e9c26e74dd3d87421f7ada9433b8cd22","name":"TechVidvan Team","description":"The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today\u2019s tech industry."}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/78942","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/comments?post=78942"}],"version-history":[{"count":0,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/posts\/78942\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media\/79033"}],"wp:attachment":[{"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/media?parent=78942"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/categories?post=78942"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techvidvan.com\/tutorials\/wp-json\/wp\/v2\/tags?post=78942"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}