{"id":28,"date":"2016-12-23T20:12:00","date_gmt":"2016-12-23T20:12:00","guid":{"rendered":"http:\/\/www.java2blog.com\/?p=28"},"modified":"2021-01-26T23:48:23","modified_gmt":"2021-01-26T18:18:23","slug":"java-semaphore-example","status":"publish","type":"post","link":"https:\/\/java2blog.com\/java-semaphore-example\/","title":{"rendered":"Java Semaphore example"},"content":{"rendered":"<div id=\"toc_container\" class=\"toc_light_blue no_bullets\"><p class=\"toc_title\">Table of Contents<\/p><ul class=\"toc_list\"><li><a href=\"#Real_time_examples\">Real time examples:<\/a><\/li><li><a href=\"#Example\">Example:<\/a><\/li><li><a href=\"#Explanation\">Explanation:<\/a><\/li><\/ul><\/div>\n<div dir=\"ltr\" style=\"text-align: left;\">In this tutorial, we are going to see about Semaphore in java.<br \/>\nSemaphore is a class in java.util.concurrent package introduced in JDK 5. Semaphore basically maintains a set of permits, so there are two methods which are mainly used for semaphore.<\/p>\n<ul style=\"text-align: left;\">\n<li>acquire<\/li>\n<li>release<\/li>\n<\/ul>\n<div>acquire() method is used to get a permit and if no. of permits reaches max allowed permits then thread has to wait to get permit which will be released by some other thread by calling release() method.<\/div>\n<div>\n<p>Semaphores are generally used to restrict the number of threads to access resources.<\/p>\n<h4 style=\"text-align: left;\"><span id=\"Real_time_examples\">Real time examples:<\/span><\/h4>\n<ul style=\"text-align: left;\">\n<li>Semaphores can be used to restrict number of database connections at a time<\/li>\n<li>Semaphores can also be used to bound any collection.<\/li>\n<\/ul>\n<div>\n<h4 style=\"text-align: left;\"><span id=\"Example\">Example:<\/span><\/h4>\n<\/div>\n<div>We will create a class BoundedArrayList which can have only 5 elements at a time. If any thread wants to add more element to the list, \u00a0thread will have to wait until any other thread remove elements from the list.<\/div>\n<div>When we add an element to the list, we will call semaphore.acquire and when we remove an element from the list, we will call semaphore.release.<\/div>\n<div>Create a class called BoundedArrayList.<\/div>\n<pre name=\"code\" class=\"\">package org.arpit.java2blog.bean;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\nimport java.util.concurrent.Semaphore;\n\npublic class BoundedArrayList {\n\n private final Semaphore semaphore;\n private List arraylist;\n\n BoundedArrayList(int limit) {\n this.arraylist = Collections.synchronizedList(new ArrayList());\n semaphore = new Semaphore(limit);\n }\n\n \/*\n * Add element to the list and call semaphore.acquire method\n * *\/\n public boolean add(T t) throws InterruptedException {\n boolean added = false;\n semaphore.acquire();\n try {\n added = arraylist.add(t);\n return added;\n } finally {\n if (!added)\n semaphore.release();\n }\n\n }\n\n \/*\n * remove element from the list and call semaphore.release method\n * *\/\n public boolean remove(T t) {\n boolean wasRemoved = arraylist.remove(t);\n if (wasRemoved)\n semaphore.release();\n return wasRemoved;\n }\n\n public void remove(int index) {\n arraylist.remove(index);\n semaphore.release();\n }\n\n public List getArraylist() {\n return arraylist;\n }\n\n public Semaphore getSemaphore() {\n return semaphore;\n }\n}<\/pre>\n<p>Create a main class BoundedArrayListMain.java<\/p>\n<pre name=\"code\">package org.arpit.java2blog.bean;\n\npublic class BoundedArrayListMain {\n\n public static void main(String[] args) throws InterruptedException {\n\n  final BoundedArrayList ba = new BoundedArrayList(5);\n  Runnable runnable1 = new Runnable() {\n\n   @Override\n   public void run() {\n    try {\n     ba.add(\"John\");\n     ba.add(\"Martin\");\n     ba.add(\"Adam\");\n     ba.add(\"Prince\");\n     ba.add(\"Tod\");\n     System.out.println(\"Available Permits : \"+ba.getSemaphore().availablePermits());\n     ba.add(\"Tony\");\n     System.out.println(\"Final list: \"+ba.getArraylist());\n    } catch (InterruptedException ie) {\n\n    }\n   }\n  };\n  Runnable runnable2 = new Runnable() {\n   @Override\n   public void run() {\n    try {\n     System.out.println(\"Before removing elements: \"+ ba.getArraylist());\n     Thread.sleep(5000);\n     ba.remove(\"Martin\");\n     ba.remove(\"Adam\");\n    } catch (InterruptedException e) {\n     e.printStackTrace();\n    }\n   }\n  };\n\n  Thread t1 = new Thread(runnable1);\n  Thread t2 = new Thread(runnable2);\n  t1.start();\n  t2.start();\n }\n\n}<\/pre>\n<p>When you run above program, you will get below output:<\/p>\n<pre name=\"code\" style=\"text-align: left;\">Available Permits : 0\nBefore removing elements: [John, Martin, Adam, Prince, Tod]\nFinal list: [John, Prince, Tod, Tony]<\/pre>\n<h4 style=\"text-align: left;\"><span id=\"Explanation\">Explanation:<\/span><\/h4>\n<ul style=\"text-align: left;\">\n<li>We have created two thread t1 and t2.<\/li>\n<li>t1 and t2 both share common list reference ba.<\/li>\n<li>When t1 adds 5 elements to the list, available permits became 0.<\/li>\n<li>Now t1 waits for another thread to remove elements, so that semaphore have some available permits.<\/li>\n<li>Another thread t2 removes elements from the list after waiting for 5 secs.<\/li>\n<li>Once t2 removes elements, t1 adds &#8220;Tony&#8221; to list.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Table of ContentsReal time examples:Example:Explanation: In this tutorial, we are going to see about Semaphore in java. Semaphore is a class in java.util.concurrent package introduced in JDK 5. Semaphore basically maintains a set of permits, so there are two methods which are mainly used for semaphore. acquire release acquire() method is used to get a [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":12656,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[212,9],"tags":[222,223],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/28"}],"collection":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/comments?post=28"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/28\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/12656"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=28"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=28"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=28"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}