{"id":25,"date":"2017-01-06T05:40:00","date_gmt":"2017-01-06T05:40:00","guid":{"rendered":"http:\/\/www.java2blog.com\/?p=25"},"modified":"2021-09-06T20:23:23","modified_gmt":"2021-09-06T14:53:23","slug":"java-exchanger-example","status":"publish","type":"post","link":"https:\/\/java2blog.com\/java-exchanger-example\/","title":{"rendered":"Java Exchanger example"},"content":{"rendered":"<div dir=\"ltr\" style=\"text-align: left;\">\n<div style=\"text-align: justify;\">Exchanger class is introduced with java 1.5 with other classes such <a href=\"http:\/\/www.java2blog.com\/concurrenthashmap-in-java\/\" target=\"_blank\" rel=\"noopener\">ConcurrentHashMap<\/a>, <a href=\"http:\/\/www.java2blog.com\/countdownlatch-in-java\/\" target=\"_blank\" rel=\"noopener\">CountDownLatch<\/a>, <a href=\"http:\/\/www.java2blog.com\/java-semaphore-example\/\" target=\"_blank\" rel=\"noopener\">Semaphores<\/a>.<\/div>\n<div style=\"text-align: justify;\">Exchanger class is used to exchange object between two threads. Exchanger simply waits until two separate threads calls exchange method, when it happens, it exchanges data supplied by threads.Two threads can pair and swap objects between them. Exchanger\u00a0class may be useful in genetic algorithms or pipeline design.<\/div>\n<p>It has two overloaded version of exchange method.<\/p>\n<ul style=\"text-align: left;\">\n<li><b>exchange(V x):<\/b> It waits for another thread to arrive at exchange point and exchange object with that thread.<\/li>\n<li><b>exchange(V x, long timeout, TimeUnit unit): <\/b>It waits for another thread for <b>specific time interval<\/b> provided in the method and exchange object with that thread.<\/li>\n<\/ul>\n<div style=\"clear: both; text-align: center;\"><\/div>\n<div>\n<div style=\"clear: both; text-align: center;\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2021\/09\/Exchanger.png\" width=\"640\" height=\"308\" border=\"0\" \/><\/div>\n<\/div>\n<div><b>Let&#8217;s understand with help of example:<\/b><\/div>\n<div>\n<p>We have two threads i.e. Producer and Consumer and they will exchange Country objects. Producer will create Country objects and Consumer will return dummy country objects.<\/p>\n<div style=\"clear: both; text-align: center;\"><\/div>\n<\/div>\n<div>\n<div style=\"clear: both; text-align: center;\"><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/java2blog.com\/wp-content\/uploads\/2021\/09\/ExchangerExample.png\" width=\"640\" height=\"292\" border=\"0\" \/><\/div>\n<\/div>\n<div>Let&#8217;s first create Country class. It just have one attribute called countryName.<\/div>\n<pre name=\"code\" class=\"\">package org.arpit.java2blog;\npublic class Country {\n\n private String countryName;\n\n public Country(String countryName) {\n super();\n this.countryName = countryName;\n }\n\n public String getCountryName() {\n return countryName;\n }\n}<\/pre>\n<p>Now we will create main class called ExchangerExampleMain.java and it will have two other classes called Producer and Consumer which will implement runnable interface.<\/p>\n<pre name=\"code\">package org.arpit.java2blog;\n\nimport java.util.concurrent.Exchanger;\n\npublic class ExchangerExampleMain {\n\n    public static void main(String[] args) {\n        Exchanger exchanger = new Exchanger();\n        \/\/ Starting two threads\n        new Thread(new Producer(exchanger)).start();\n        new Thread(new Consumer(exchanger)).start();\n    }\n}\n\nclass Producer implements Runnable {\n\n    Exchanger ex;\n    Producer(Exchanger ex){\n        this.ex = ex;\n\n    }\n    @Override\n    public void run() {\n        for(int i = 0; i < 2; i ++){\n          Country country=null ;\n         if(i==0)\n               country =new Country(\"India\");\n         else\n          country =new Country(\"Bhutan\");\n\n            try {\n                \/\/ exchanging with an dummy Country object\n                Country dummyCountry = ex.exchange(country);\n                System.out.println(\"Got country object from Consumer thread : \"+dummyCountry.getCountryName());\n            } catch (InterruptedException e) {\n                System.out.println(e);\n            }\n        }\n    }\n}\n\nclass Consumer implements Runnable {\n\n    Exchanger ex;\n    Consumer(Exchanger ex){\n        this.ex = ex;\n    }\n    @Override\n    public void run() {\n        for(int i = 0; i < 2; i ++){\n            try {\n                \/\/ Getting Country object from producer thread\n                \/\/ giving dummy country object in return\n                Country country = ex.exchange(new Country(\"Dummy\"));\n                System.out.println(\"Got country object from Producer thread : \"+country.getCountryName());\n\n            } catch (InterruptedException e) {\n                System.out.println(e);\n            }\n        }\n    }\n}<\/pre>\n<p>When you run above program, you will get below output.<\/p>\n<pre name=\"code\">Got country object from Consumer thread : Dummy\nGot country object from Producer thread : India\nGot country object from Consumer thread : Dummy\nGot country object from Producer thread : Bhutan<\/pre>\n<p>If you notice, producer has exchanged two country object (India and Bhutan) with consumer and got dummy country objects in return.<br \/>\nIf you want to understand more realistic use of Exchanger. Producer and consumer may exchange buffers. When buffer is full, Producer will provide full buffer to consumer and Consumer will return empty buffer in return.<\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Exchanger class is introduced with java 1.5 with other classes such ConcurrentHashMap, CountDownLatch, Semaphores. Exchanger class is used to exchange object between two threads. Exchanger simply waits until two separate threads calls exchange method, when it happens, it exchanges data supplied by threads.Two threads can pair and swap objects between them. Exchanger\u00a0class may be useful [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":12650,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"_mi_skip_tracking":false},"categories":[212,9],"tags":[],"_links":{"self":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/25"}],"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=25"}],"version-history":[{"count":0,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/posts\/25\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media\/12650"}],"wp:attachment":[{"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/media?parent=25"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/categories?post=25"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/java2blog.com\/wp-json\/wp\/v2\/tags?post=25"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}