{"id":8397,"date":"2014-06-27T10:06:20","date_gmt":"2014-06-27T10:06:20","guid":{"rendered":"https:\/\/www.whizlabs.com\/?p=8397"},"modified":"2020-09-01T07:21:45","modified_gmt":"2020-09-01T07:21:45","slug":"uses-of-synchronized-keyword-ijava","status":"publish","type":"post","link":"https:\/\/www.whizlabs.com\/blog\/uses-of-synchronized-keyword-ijava\/","title":{"rendered":"Uses Of Synchronized Keyword In Java"},"content":{"rendered":"<p>Concurrency problems are most common problems among multi-threaded applications. If one single thread is executing, it can gracefully get access to the resources and complete its execution. The problem arises when multiple threads competing with each other to get hold of resources. Due to this variety of problems can occur like inconsistent data, dead lock situations etc. Java mitigates these problems by synchronizing resource access so that single thread get to access resources and releases the resource for the next thread to process. This process is known as \u201csynchronization\u201d and we achieve synchronization using keyword \u201csynchronized\u201d.<\/p>\n<p>The &#8220;synchronized&#8221; keyword can be used in two contexts:<\/p>\n<ul>\n<li>In methods by defining required methods as <i>synchronized<\/i><\/li>\n<li>By making block of code <i>synchronized<\/i><\/li>\n<\/ul>\n<p>Synchronization works by using locks. If any object has synchronized method code, then object will also contain a built-in lock. When any thread first gets into the synchronized method, that thread acquires the lock associated with the object. We can also call object lock as monitor. Since each object has only one lock, if any thread acquires the lock, no other thread cannot acquire the lock until the first thread releases the lock. This ensures that no other thread enters into synchronized method code thus preventing from inconsistent data.<\/p>\n<p>The following are few rules with respect to synchronized keyword.<\/p>\n<ul>\n<li>Only methods and block of code can be synchronized, making variables or classes synchronized results in compilation error.<\/li>\n<li>Each object is associated with one and only one lock.<\/li>\n<li>If any thread\u2019s sleep() method is called, the thread will go to sleep to sleep by keeping its acquired object lock. It doesn\u2019t release the lock.<\/li>\n<li>A thread can acquire multiple locks belonging to different objects. But each object contains only one lock.<\/li>\n<\/ul>\n<h4>Using <i>synchronized<\/i> in methods<\/h4>\n<p>The following code snippet makes debitFromAccount method synchronized.<\/p>\n<p><code><br \/>\npublic synchronized boolean debitFromAccount(int accountId, double amount) {<br \/>\n\/\/ business logic to debit funds from account<br \/>\n}<br \/>\n<\/code><\/p>\n<p>As we marked above method synchronized, only one thread which has the object lock can execute this method and perform transaction. Other threads are in waiting state until the first thread releases the lock.<\/p>\n<h4>Using <i>synchronized<\/i> in block of code<\/h4>\n<p>Since synchronizing controls multiple thread accessing resources, this indeed comes with performance penalties. So instead of synchronizing entire method, we can synchronize a block of code as shown below. We can call this block of code as synchronized block.<\/p>\n<p><code><br \/>\nclass Account {<br \/>\npublic boolean debitFromAccount(int accountId, double amount) {<\/code><\/p>\n<p>\/\/ code that needs to be executed in non-synchronized context.<\/p>\n<p>synchronized(this) {<br \/>\n\/\/ business logic to debit funds from account<\/p>\n<p>}<br \/>\n}<br \/>\n}<\/p>\n<p>As we see in above code snippet, instead of synchronizing entire method, we synchronized the block of code which needs to be executed in synchronized context. Also, the above code is acquiring lock on the current instance.<\/p>\n<p>When thread is executing synchronized methods, the lock will be acquired on the object whose method is being executed. On the other hand, when the thread is executing block of code, we specify which object\u2019s lock needs to be acquired. The advantage of synchronizing block of code is, we can also specify other third-party objects as well, so that thread will acquire locks on these objects.<\/p>\n<h4>How locks are acquired on static methods<\/h4>\n<p>Static methods can also be synchronized. Since there is no object in the static context, also our data is directly associated with class, the lock needs to be acquired on the entire class itself. In the case of static synchronized methods, the thread will acquire the lock on the <i>java.lang.Class<\/i> instance which is representing the Class.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Concurrency problems are most common problems among multi-threaded applications. If one single thread is executing, it can gracefully get access to the resources and complete its execution. The problem arises when multiple threads competing with each other to get hold of resources. Due to this variety of problems can occur like inconsistent data, dead lock situations etc. Java mitigates these problems by synchronizing resource access so that single thread get to access resources and releases the resource for the next thread to process. This process is known as \u201csynchronization\u201d and we achieve synchronization using keyword \u201csynchronized\u201d. The &#8220;synchronized&#8221; keyword can [&hellip;]<\/p>\n","protected":false},"author":220,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[13],"tags":[1507],"class_list":["post-8397","post","type-post","status-publish","format-standard","hentry","category-java","tag-synchronized-threads-java"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false,"profile_24":false,"profile_48":false,"profile_96":false,"profile_150":false,"profile_300":false,"tptn_thumbnail":false,"web-stories-poster-portrait":false,"web-stories-publisher-logo":false,"web-stories-thumbnail":false},"uagb_author_info":{"display_name":"Aditi Malhotra","author_link":"https:\/\/www.whizlabs.com\/blog\/author\/aditi\/"},"uagb_comment_info":10,"uagb_excerpt":"Concurrency problems are most common problems among multi-threaded applications. If one single thread is executing, it can gracefully get access to the resources and complete its execution. The problem arises when multiple threads competing with each other to get hold of resources. Due to this variety of problems can occur like inconsistent data, dead lock&hellip;","_links":{"self":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/8397","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/users\/220"}],"replies":[{"embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/comments?post=8397"}],"version-history":[{"count":1,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/8397\/revisions"}],"predecessor-version":[{"id":76003,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/posts\/8397\/revisions\/76003"}],"wp:attachment":[{"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/media?parent=8397"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/categories?post=8397"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.whizlabs.com\/blog\/wp-json\/wp\/v2\/tags?post=8397"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}