{"id":280,"date":"2021-02-03T20:38:09","date_gmt":"2021-02-03T20:38:09","guid":{"rendered":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/?page_id=280"},"modified":"2021-02-05T16:33:02","modified_gmt":"2021-02-05T16:33:02","slug":"thread-coordination-communication","status":"publish","type":"page","link":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/","title":{"rendered":"Thread Coordination &#038; Communication"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_85 counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a6d4953b03bf\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #999;color:#999\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #999;color:#999\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a6d4953b03bf\"  aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Monitors_Synchronization_Deadlocks\" >Monitors, Synchronization &amp; Deadlocks<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Why_do_we_need_Synchronization\" >Why do we need Synchronization?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Example_A_Steam_Boiler\" >Example: A Steam Boiler<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Race_Conditions\" >Race Conditions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Monitors\" >Monitors<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Synchronization\" >Synchronization<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Example_A_Fixed_Steam_Boiler\" >Example: A Fixed Steam Boiler<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Deadlock\" >Deadlock<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Starvation_Livelock\" >Starvation &amp; Livelock<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Starvation\" >Starvation<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Livelock\" >Livelock<\/a><\/li><\/ul><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Thread_Coordination\" >Thread Coordination<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#ProducerConsumer_Relationships\" >Producer\/Consumer Relationships<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-14\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Conditions\" >Conditions<\/a><ul class='ez-toc-list-level-5' ><li class='ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-15\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#The_wait_Method\" >The wait() Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-16\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#The_notify_Method\" >The notify() Method<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-17\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Other_wait_Methods\" >Other wait() Methods<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-5'><a class=\"ez-toc-link ez-toc-heading-18\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#The_notifyAll_Method\" >The notifyAll() Method<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-19\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#A_ProducerConsumer_Example\" >A Producer\/Consumer Example<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-20\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Communication_Between_Threads\" >Communication Between Threads<\/a><ul class='ez-toc-list-level-4' ><li class='ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-21\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#Using_Pipes_to_Communicate_between_Threads\" >Using Pipes to Communicate between Threads<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-4'><a class=\"ez-toc-link ez-toc-heading-22\" href=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/course-topics\/threads\/thread-coordination-communication\/#An_Example\" >An Example<\/a><\/li><\/ul><\/li><\/ul><\/nav><\/div>\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Monitors_Synchronization_Deadlocks\"><\/span>Monitors, Synchronization &amp; Deadlocks<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Why_do_we_need_Synchronization\"><\/span>Why do we need Synchronization?<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s look at an example of a Java program where we ignore the problem, and see what trouble we get into.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_A_Steam_Boiler\"><\/span>Example: A Steam Boiler<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The following program is a simple emulation of a steam boiler. The boiler has a number of burners (this is a big boiler!), each one of which is programmed to burn fuel to keep the steam pressure up, unless the pressure exceeds a certain safety limit.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Class&nbsp;<strong>SteamBoiler<\/strong>&nbsp;represents the boiler, and class&nbsp;<strong>Burner<\/strong>&nbsp;represents a single burner. Each burner runs as a separate thread, and calls its <strong>burn()<\/strong> method to &#8220;burn fuel&#8221;. The&nbsp;<strong>burn()<\/strong>&nbsp;method has a check to make sure that the pressure does not go beyond the safety limit.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">You&#8217;ll note that each burner just kicks in once, and then stops &#8212; i.e. its thread dies. This is not realistic, but is done to keep things relatively simple. When all the threads have died, the main program prints out the resulting pressure, and exits.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s the code:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage unsynchronized;\n\n\/**\n *  NOTE: This implementation of the SteamBoiler class is implemented\n *  without regard to synchronization.  Because of this, it fails\n *  to maintain boiler pressure below the safety limit.\n *\/\npublic class SteamBoiler\n{\n  public static final int PRESSURE_LIMIT = 20;\n  public static final int BURNER_COUNT = 10;\n  \n  public Burner&#x5B;] start()\n  {\n    Burner&#x5B;] burners = new Burner&#x5B;BURNER_COUNT];\n    for (int burner = 0; burner &lt; BURNER_COUNT; burner++)\n    {\n      burners&#x5B;burner] = new Burner(this);\n      burners&#x5B;burner].start();\n    }\n    \n    return burners;\n  }\n  \n  public int getPressure()\n  {\n    return m_pressure;\n  }\n  \n  public void setPressure(int pressure)\n  {\n    m_pressure = pressure;\n  }\n  \n  public static void main(String&#x5B;] args)\n  {\n    SteamBoiler boiler = new SteamBoiler();\n    \n    Burner&#x5B;] burners = boiler.start();\n    \n    for (int burner = 0; burner &lt; BURNER_COUNT; burner++)\n    {\n      try\n      {\n        burners&#x5B;burner].join();     \/\/ Wait for thread to finish\n      }\n      catch (InterruptedException e)\n      {\n        \/\/ This thread was interrupted.\n      }\n    }\n    \n    System.out.println(&quot;Pressure reads &quot; + boiler.getPressure() +\n        &quot;, limit is &quot; + PRESSURE_LIMIT);\n  }\n  \n  \/\/\/\/\/\/\/ Data \/\/\/\/\/\/\n  private int m_pressure = 0;\n}\n\nclass Burner extends Thread\n{\n  public static final int PRESSURE_INCREMENT = 15;\n  \n  public Burner(SteamBoiler boiler)\n  {\n    m_boiler = boiler;\n  }\n  \n  public void run()\n  {\n    burn();\n  }\n  \n  private void burn()\n  {\n    if (m_boiler.getPressure() &lt;\n        SteamBoiler.PRESSURE_LIMIT - PRESSURE_INCREMENT)\n    {\n      \/\/ Wait to simulate delay\n      try\n      {\n        sleep(100);\n      }\n      catch (InterruptedException e)\n      {\n        \/\/ Ignore\n      }\n      \n      m_boiler.setPressure( m_boiler.getPressure() +\n          PRESSURE_INCREMENT );\n    }\n  }\n  \n  \/\/\/\/\/ Private data \/\/\/\/\/\/\n  private SteamBoiler m_boiler;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">However, when the program is run, you&#8217;ll find that it outputs the following:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Pressure reads 150, limit is 20<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">(The first number will vary because of thread timing variations.)<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s a program that uses the above class and displays the boiler pressure in a more graphical form:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage unsynchronized;\n\nimport java.awt.BorderLayout;\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.FlowLayout;\nimport java.awt.Graphics;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport javax.swing.BorderFactory;\nimport javax.swing.JApplet;\nimport javax.swing.JButton;\nimport javax.swing.JFrame;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport unsynchronized.SteamBoiler;\n\n\/**\n *  This class provides a visual representation of the SteamBoiler.\n *\/\npublic class SteamBoilerFrame extends JFrame implements Runnable\n{\n  \/**\n   * Main entry point\n   *\/\n  public static void main(String&#x5B;] args)\n  {\n    SteamBoilerFrame frame = new SteamBoilerFrame();\n    frame.setDefaultLookAndFeelDecorated(true);\n    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);\n    frame.setSize(300, 200);\n    frame.setVisible(true);\n  }\n  \n  public SteamBoilerFrame()\n  {\n    setTitle(&quot;Steam Boiler&quot;);\n    m_gauge = new PressureGauge( new SteamBoiler() );\n    setContentPane( createBoilerLayout() );\n    \/\/ Start this thread\n    m_timer = new Thread(this);\n    m_timer.start();    \/\/ Start the timer\n  }\n  \n  public void stop()\n  {\n    m_timer = null; \/\/ Stop the timer\n  }\n  \n  private JPanel createBoilerLayout()\n  {\n    JPanel panel = new JPanel( new BorderLayout() );\n    panel.setBackground(Color.lightGray);\n    \n    JLabel label = new JLabel(&quot;Steam Boiler (Max Pressure = &quot; +\n                              SteamBoiler.PRESSURE_LIMIT + &quot;)&quot;\n                              );\n    JPanel north = new JPanel( new FlowLayout(FlowLayout.CENTER) );\n    north.add(label);\n    panel.add(north, BorderLayout.NORTH);\n    \n    panel.add(m_gauge, BorderLayout.CENTER);\n    \n    JPanel south = new JPanel( new FlowLayout(FlowLayout.CENTER) );\n    m_startButton.addActionListener( new ActionListener()\n      {\n        public void actionPerformed(ActionEvent event)\n        {\n          m_startButton.setEnabled(false);\n          m_gauge.getBoiler().start();   \/\/ Start the boiler\n        }\n      }\n    );\n    south.add(m_startButton);\n    \n    m_lastPressure = m_gauge.getPressure();\n    m_pressureText = new JLabel(PRESSURE_TEXT + m_lastPressure);\n    south.add(m_pressureText);\n    \n    m_resetButton.addActionListener( new ActionListener()\n      {\n        public void actionPerformed(ActionEvent event)\n        {\n          m_gauge.setBoiler( new SteamBoiler() );\n          m_startButton.setEnabled(true);\n        }\n      }\n    );\n    south.add(m_resetButton);\n    panel.add(south, BorderLayout.SOUTH);\n    \n    return panel;\n  }\n  \n    \/*\n     *   This constitutes a timer thread to refresh the gauge\n     *   on a regular basis.\n     *\/\n  public void run()\n  {\n    while (m_timer != null)\n    {\n      try\n      {\n        Thread.sleep(100);\n      }\n      catch (InterruptedException e)\n      {\n        \/\/ Ignore\n      }\n      \n      \/\/ Repaint if the pressure has changed since last time\n      int pressure = m_gauge.getPressure();\n      if (pressure != m_lastPressure)\n      {\n        m_lastPressure = pressure;\n        m_pressureText.setText(PRESSURE_TEXT + pressure);\n        m_gauge.repaint();\n      }\n    }\n  }\n  \n  \/\/\/\/\/\/\/\/\/ Private Data \/\/\/\/\/\/\n  private boolean         m_laidOut = false;\n  private Thread          m_timer;\n  private PressureGauge   m_gauge;\n  private JButton         m_startButton = new JButton(&quot;Burn!&quot;);\n  private JButton         m_resetButton = new JButton(&quot;Reset&quot;);\n  private JLabel          m_pressureText;\n  private int             m_lastPressure = 0;\n  \n  private static final String PRESSURE_TEXT = &quot;Pressure = &quot;;\n}\n\nclass PressureGauge extends JPanel\n{\n  public PressureGauge(SteamBoiler boiler)\n  {\n    setBoiler(boiler);\n  }\n  \n  public void setBoiler(SteamBoiler boiler)\n  {\n    m_boiler = boiler;\n    repaint();\n  }\n  \n  public SteamBoiler getBoiler()\n  {\n    return m_boiler;\n  }\n  \n  public int getPressure()\n  {\n    return m_boiler.getPressure();\n  }\n  \n  public void paintComponent(Graphics g)\n  {\n    super.paintComponent(g);\n    Dimension dim = getSize();\n    int x = (dim.width - OUTER_WIDTH)\/2;\n    int y = 0;\n    \n    \/\/ Draw outer white area\n    g.setColor(Color.WHITE);\n    g.fillRect(x, y, OUTER_WIDTH, dim.height);\n    \n    \/\/ Draw outline\n    g.setColor(Color.black);\n    int width = OUTER_WIDTH - INSET - INSET;\n    int height = dim.height - INSET - INSET;\n    g.drawRect(x + INSET - 1, y + INSET - 1, width + 1, height + 1);\n    \n    \/\/ Draw the &quot;mercury&quot;\n    Color color = Color.blue;\n    if (getPressure() &gt; SteamBoiler.PRESSURE_LIMIT)\n      color = Color.red;\n    g.setColor(color);\n    \n    float factor = (float) getPressure() \/ (float) (SteamBoiler.PRESSURE_LIMIT * 10);\n    height = (int) ((float)height * factor);\n    g.fillRect(x + INSET, dim.height - height - INSET, width, height);\n  }\n  \n  \/\/\/\/\/ Private data \/\/\/\/\/\/\/\n  private static final int OUTER_WIDTH = 20;\n  private static final int INSET = 5;\n  \n  private SteamBoiler m_boiler;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">and here&#8217;s what it produces (a video):<\/p>\n\n\n\n<figure class=\"wp-block-video alignleft\"><video height=\"418\" style=\"aspect-ratio: 612 \/ 418;\" width=\"612\" controls src=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-content\/uploads\/2021\/02\/UnsynchonizedSteamBoiler.mov\"><\/video><\/figure>\n\n\n\n<div style=\"height:9px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p>Perhaps I should add some explosive effects?<\/p><\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">So what&#8217;s going on?<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Race_Conditions\"><\/span>Race Conditions<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The problem is a classical problem in multi-threaded code &#8212; a&nbsp;<em><strong>race condition<\/strong><\/em>. What you probably expected to happen was:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>Thread A reads the pressure gauge<\/strong><\/li><li><strong>Thread A updates the pressure gauge<\/strong><\/li><li><strong>Thread B reads the pressure gauge<\/strong><\/li><li><strong>Thread B updated the pressure gauge<\/strong><\/li><\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">However, what actually happens is more like:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><strong>Thread A reads the pressure gauge<\/strong><\/li><li><strong>Thread B reads the pressure gauge<\/strong><\/li><li><strong>Thread A updates the pressure gauge<\/strong><\/li><li><strong>Thread B updates the pressure gauge<\/strong><\/li><\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">In other words, Thread A was preempted by Thread B, and then back again, and then again. The result is that Thread A&#8217;s update is overwritten by Thread B, and the check that you thought was happening is made useless.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">When you have multiple concurrent activities updating a shared data item, you have to be more careful &#8212; you have to&nbsp;<em><strong>synchronize<\/strong><\/em>&nbsp;access to that data item.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Monitors\"><\/span>Monitors<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The concept of a&nbsp;<em><strong>monitor<\/strong><\/em>&nbsp;was pioneered in the 1970s by <strong>C.A.R. Hoare<\/strong> and <strong>Per Brinch Hansen<\/strong>.&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A monitor applies the principle of&nbsp;<em><strong>mutual exclusion<\/strong><\/em>&nbsp;to a set of procedures. When mutual exclusion occurs, only a single thread can have access to a shared resource at a time. Other threads that attempt to access the shared resource are forced to wait until the thread that is accessing the resource has done with it..<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In order for a thread to gain the necessary access to a shared resource, it must acquire a&nbsp;<em><strong>lock<\/strong><\/em>&nbsp;and hold it until the thread has completed the necessary actions on that resource. Then it must release the lock, so that any waiting threads may compete to acquire the lock. Only one of the threads will win, and the rest continue to wait.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This mechanism assures that access to the shared resource is&nbsp;<em><strong>serialized<\/strong><\/em>, so that only one thread may access the resource at a time.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In general, it is good practice to minimize the amount of time that a thread can hold a lock. If a thread holds a lock too long, it can negatively impact the performance of the system.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p><strong><u>Note:&nbsp;<\/u><\/strong>Per Brinch Hansen, one of the pioneers of monitors was not pleased at what he saw in how Java implemented the idea of a monitor.&nbsp; See&nbsp;<a rel=\"noreferrer noopener\" href=\"http:\/\/brinch-hansen.net\/papers\/1999b.pdf\" target=\"_blank\">http:\/\/brinch-hansen.net\/papers\/1999b.pdf<\/a>&nbsp;for more details.<\/p><\/blockquote>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Synchronization\"><\/span>Synchronization<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">In Java,&nbsp;<em><strong>every object has an associated monitor<\/strong><\/em>&nbsp;which may be used to serialize access to that object. Also, every class has an associated monitor to serialize access to the class. The Java Virtual Machine implements the necessary support for these monitors.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Java language adds a construct to allow a programmer to specify when a monitor is to be used &#8212; the&nbsp;<strong>synchronized<\/strong>&nbsp;keyword:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em><strong>The&nbsp;<\/strong><\/em><em><strong>synchronized<\/strong><\/em><em><strong>&nbsp;statement performs two special actions relevant only to multithreaded operation:<\/strong><\/em><\/p>\n\n\n\n<ol class=\"wp-block-list\"><li><em><strong>After computing a reference to an object but before executing its body, it locks a lock associated with the object.<\/strong><\/em><\/li><li><em><strong>After execution of the body has completed, either normally or abruptly, it unlocks that same lock. As a convenience, a method may be declared&nbsp;<\/strong><\/em><em><strong>synchronized<\/strong><\/em><em><strong>; such a method behaves as if its body were contained in a&nbsp;<\/strong><\/em><em><strong>synchronized<\/strong><\/em><em><strong>&nbsp;statement.<\/strong><\/em><\/li><\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><em><strong>(The Java Virtual Machine Specification, by Tim Lindholm &amp; Frank Yellin, published by Addison Wesley, 1997, page 53.)<\/strong><\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here are some examples of the use of synchronized keyword:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [9,14,21,30]; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\npublic class SharedResource\n{\n    \/\/ ...\n\n    private String m_value = &quot;&quot;;\n\n    public synchronized void setValue(String value)  \/\/ 1\n    {\n        m_value = value;\n    }\n\n    public synchronized String getValue()\t     \/\/ 2\n    {\n        return m_value;\n    }\n\n    private static int m_count = 0;\n\n    public static synchronized void incrementCount()  \/\/ 3\n    {\n        m_count++;\n    }\n\n    private Double m_salary = new Double(32000.0);\n\n    public void giveRaise(double percent)\n    {\n        synchronized (m_salary) \t\t       \/\/ 4\n        {\n            double salary = m_salary.doubleValue();\n            salary += salary * percent \/100;\n            m_salary = new Double(salary);\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Methods&nbsp;<strong>1<\/strong>&nbsp;and&nbsp;<strong>2<\/strong>, because they are instance methods,&nbsp;<em><strong>synchronize on the<\/strong><\/em>&nbsp;<strong>object&#8217;s (or instance&#8217;s) monitor<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Method&nbsp;<strong>3<\/strong>, because it is a class (static) method,&nbsp;<em><strong>synchronizes on the<\/strong><\/em>&nbsp;<strong>class&#8217; monitor<\/strong><em>.<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;synchronized&nbsp;statement at&nbsp;<strong>4<\/strong>&nbsp;specifies that it&nbsp;<em><strong>synchronizes on<\/strong><\/em>&nbsp;<strong>m_salary<\/strong><strong>,&nbsp;<\/strong><em>an instance of class&nbsp;<\/em><em>Double<\/em><em>.<\/em><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p><em><strong><u>Note:<\/u><\/strong><\/em>&nbsp;The synchronization may not be on an instance of a primitive type, such as&nbsp;double.<\/p><\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">Note that methods&nbsp;<strong>getValue()<\/strong>,&nbsp;<strong>incrementCount()<\/strong>&nbsp;and&nbsp;<strong>raiseSalary()<\/strong>&nbsp;may all be executing concurrently in different threads,&nbsp;<em><strong>because they synchronize on different monitors<\/strong><\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A thread may call a&nbsp;synchronized&nbsp;method on an object for which it already holds the lock. This is called&nbsp;<em><strong>reacquiring the lock<\/strong><\/em>, and is allowed because Java monitors are&nbsp;<em><strong>reentrant<\/strong><\/em>. Because of this, a single thread cannot&nbsp;<em><strong>deadlock<\/strong><\/em>&nbsp;itself on a lock it already holds.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Example_A_Fixed_Steam_Boiler\"><\/span>Example: A Fixed Steam Boiler<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Now, let&#8217;s go back to our&nbsp;<strong>SteamBoiler<\/strong>&nbsp;class, and change the&nbsp;<strong>burn()<\/strong>&nbsp;method in class <strong>Burner<\/strong> to:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [3,21]; title: ; quick-code: false; notranslate\" title=\"\">\nprivate void burn()\n{\n    synchronized (m_boiler)\n    {\n        if (m_boiler.getPressure() &lt; \n                   SteamBoiler.PRESSURE_LIMIT - PRESSURE_INCREMENT)\n        {\n            \/\/ Wait to simulate delay\n            try\n            {\n                sleep(100);\n            }\n            catch (InterruptedException e)\n            {\n                \/\/ Ignore\n            }\n                \n            m_boiler.setPressure( m_boiler.getPressure() + \n                                  PRESSURE_INCREMENT );\n        }\n    }\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">The only change is to surround the code with a&nbsp;<strong>synchronized<\/strong>&nbsp;statement, specifying the instance of&nbsp;<strong>SteamBoiler<\/strong>&nbsp;as the object on which to synchronize.&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Why did I choose to synchronize on the instance of&nbsp;<strong>SteamBoiler<\/strong>? Why did I not simply make the <strong>burn()<\/strong> method&nbsp;<strong>synchronized<\/strong>?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">To show it works, here&#8217;s the fixed&nbsp;<strong>SteamBoiler <\/strong>class:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; highlight: [76,94]; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\n\/**\n *  NOTE: This implementation of the SteamBoiler class is implemented\n *  with regard to synchronization.  \n *\/\npublic class SteamBoiler\n{\n  public static final int PRESSURE_LIMIT = 20;\n  public static final int BURNER_COUNT = 10;\n  \n  public Burner&#x5B;] start()\n  {\n    Burner&#x5B;] burners = new Burner&#x5B;BURNER_COUNT];\n    for (int burner = 0; burner &lt; BURNER_COUNT; burner++)\n    {\n      burners&#x5B;burner] = new Burner(this);\n      burners&#x5B;burner].start();\n    }\n    \n    return burners;\n  }\n  \n  public int getPressure()\n  {\n    return m_pressure;\n  }\n  \n  public void setPressure(int pressure)\n  {\n    m_pressure = pressure;\n  }\n  \n  public static void main(String&#x5B;] args)\n  {\n    SteamBoiler boiler = new SteamBoiler();\n    \n    Burner&#x5B;] burners = boiler.start();\n    \n    for (int burner = 0; burner &lt; BURNER_COUNT; burner++)\n    {\n      try\n      {\n        burners&#x5B;burner].join();     \/\/ Wait for thread to finish\n      }\n      catch (InterruptedException e)\n      {\n        \/\/ This thread was interrupted.\n      }\n    }\n    \n    System.out.println(&quot;Pressure reads &quot; + boiler.getPressure() +\n      &quot;, limit is &quot; + PRESSURE_LIMIT);\n  }\n  \n  \/\/\/\/\/\/\/ Data \/\/\/\/\/\/\n  private int m_pressure = 0;\n}\n\nclass Burner extends Thread\n{\n  public static final int PRESSURE_INCREMENT = 15;\n  \n  public Burner(SteamBoiler boiler)\n  {\n    m_boiler = boiler;\n  }\n  \n  public void run()\n  {\n    burn();\n  }\n  \n  private void burn()\n  {\n    synchronized (m_boiler)\n    {\n      if (m_boiler.getPressure() &lt;\n        SteamBoiler.PRESSURE_LIMIT - PRESSURE_INCREMENT)\n      {\n        \/\/ Wait to simulate delay\n        try\n        {\n          sleep(100);\n        }\n        catch (InterruptedException e)\n        {\n          \/\/ Ignore\n        }\n        \n        m_boiler.setPressure( m_boiler.getPressure() +\n          PRESSURE_INCREMENT );\n      }\n    }\n  }\n  \n  \/\/\/\/\/ Private data \/\/\/\/\/\/\n  private SteamBoiler m_boiler;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">When this program is run, it outputs:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>Pressure reads 15, limit is 20<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The graphical test program remains unchanged, and now produces (a video):<\/p>\n\n\n\n<figure class=\"wp-block-video alignleft\"><video height=\"418\" style=\"aspect-ratio: 612 \/ 418;\" width=\"612\" controls src=\"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-content\/uploads\/2021\/02\/SynchronizedSteamBoiler.mov\"><\/video><figcaption>Much safer!<\/figcaption><\/figure>\n\n\n\n<div style=\"height:20px\" aria-hidden=\"true\" class=\"wp-block-spacer\"><\/div>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Deadlock\"><\/span>Deadlock<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">We said that, for a given thread that has already acquired the lock on a monitor, monitors are <em><strong>reentrant<\/strong><\/em>. However, if two (or more) threads compete for the same two (or more) resources, there is the possibility of <em><strong>deadlock<\/strong><\/em>, unless measures are taken to prevent it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, imagine that we&#8217;re writing a program to transfer funds from one bank account to another, and we want to ensure that we have no problems when we are accessing accounts from different threads. <\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s a possible program to do that:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\n\/**\n*  This class will create a deadlock situation.\n*\/\npublic class Deadlock\n{\n    public static void main(String&#x5B;] args)\n    {\n        Account a1 = new Account(&quot;Account 1&quot;, 10000);\n        Account a2 = new Account(&quot;Account 2&quot;, 30000);\n        Thread threadA = \n            new TransferFundsThread(&quot;Thread A&quot;, a1, a2, 5);\n        Thread threadB = \n            new TransferFundsThread(&quot;Thread B&quot;, a2, a1, 20);\n        threadA.start();\n        threadB.start();\n    }\n}\n\nclass Account\n{\n    public Account(String name, int balance)\n    {\n        m_name = name;\n        m_balance = balance;\n    }\n    \n    public int getBalance()\n    {\n        return m_balance;\n    }\n    \n    public void setBalance(int newBalance)\n    {\n        m_balance = newBalance;\n    }\n    \n    public String getName()\n    {\n        return m_name;\n    }\n    \n    private String m_name;\n    private int    m_balance;\n}\n\nclass TransferFundsThread extends Thread\n{\n    public TransferFundsThread(String name, \n                               Account from, \n                               Account to, \n                               int amount)\n    {\n        super(name);\n        m_from   = from;\n        m_to     = to;\n        m_amount = amount;\n    }\n    \n    public void run()\n    {\n        transferFunds();\n    }\n    \n    \/**\n     *  In order to transfer funds safely, we need to be able \n     *  to hold a lock on both the m_from and the m_to accounts, \n     *  and not release the locks until the transfer is completed.\n     *  NOTE: This version does not consider the possibility that \n     *  there may be insufficient funds available.  This has been \n     *  omitted to simplify the example, but would have to be done \n     *  in the real world.\n     *\/\n    private void transferFunds()\n    {\n        synchronized (m_from)\n        {\n            System.out.println(getName() + \n                               &quot;: Getting balance from &quot; + \n                               m_from.getName());\n            int balance1 = m_from.getBalance();\n            System.out.println(getName() + \n                               &quot;: Balance from &quot; + \n                               m_from.getName() + \n                               &quot; = &quot; + balance1);\n                    \n            try\n            {\n                sleep(100);         \/\/ insert delay\n            }\n            catch (InterruptedException e)\n            {\n                \/\/ ignore\n            }\n            \n            synchronized (m_to)\n            {\n                System.out.println(getName() + \n                                   &quot;: Getting balance from &quot; + \n                                   m_to.getName());\n                int balance2 = m_to.getBalance();\n                System.out.println(getName() + \n                                   &quot;: Balance from &quot; + \n                                   m_to.getName() + \n                                   &quot; = &quot; + balance2);\n                                   \n                if (balance1 &gt;= m_amount)\n                {\n                    System.out.println(getName() + \n                                       &quot;: Withdrawing funds from &quot; +\n                                       m_from.getName());\n                    m_from.setBalance(balance1 - m_amount);\n                    System.out.println(getName() + \n                                       &quot;: Depositing funds into &quot; +\n                                       m_to.getName());\n                    m_to.setBalance(balance2 + m_amount);\n                    \n                    System.out.println(getName() + \n                                       &quot;: New balances are:\\n&quot; +\n                                       &quot;  &quot; + m_from.getName() + \n                                       &quot; = &quot; + \n                                       m_from.getBalance() + &quot;\\n&quot; +\n                                       &quot;  &quot; + m_to.getName() + &quot; = &quot; +\n                                       m_to.getBalance() );\n                }\n            }\n        }\n    }\n    \n    \/\/\/ Private data \/\/\/\n    private Account m_from;\n    private Account m_to;\n    private int     m_amount;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">But when you run the program, it outputs the following:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Thread A: Getting balance from Account 1\nThread B: Getting balance from Account 2\nThread A: Balance from Account 1 = 10000\nThread B: Balance from Account 2 = 30000<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">and then it stops. What&#8217;s happening? Well, if you&#8217;re running the program from a regular console window (for example, an MS-DOS window on Microsoft Windows), using the java program (not JRE), you can force a stack dump if you set the keyboard focus to the console window and press the proper keystroke combination:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>On Microsoft Windows, press&nbsp;<strong>&lt;CTRL&gt;Break<\/strong>&nbsp;(that is, hold the CTRL key down and press Break)<\/li><li>On UNIX, press&nbsp;<strong>&lt;CTRL&gt;\\<\/strong>&nbsp;(that is, hold the CTRL key down and press the backslash key)<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">and you will get output that looks something like this (this one was generated on Microsoft Windows):<\/p>\n\n\n\n<pre class=\"wp-block-preformatted smaller-font\"><strong>Full thread dump:\n    \"Thread B\" (TID:0x133d0f0, sys_thread_t:0xd26150, Win32ID:0x14b, state:MW) prio=5\n        threads.TransferFundsThread.transferFunds(Deadlock.java:70)\n        threads.TransferFundsThread.run(Deadlock.java:55)\n    \"Thread A\" (TID:0x133d110, sys_thread_t:0xd26210, Win32ID:0x15e, state:MW) prio=5\n        threads.TransferFundsThread.transferFunds(Deadlock.java:70)\n        threads.TransferFundsThread.run(Deadlock.java:55)\n    \"SymcJIT-LazyCompilation-0\" (TID:0x133cf58, sys_thread_t:0xd269c0, Win32ID:0x141, state:CW) prio=2\n        SymantecJITCompilationThread.run(JITcompilationthread.java, Compiled Code)\n    \"SymcJIT-LazyCompilation-PA\" (TID:0x133cf20, sys_thread_t:0xd251f0, Win32ID:0x158, state:CW) prio=10\n        java.lang.Object.wait(Object.java:307)\n        SymantecJITCompilationThread.run(JITcompilationthread.java, Compiled Code)\n    \"Finalizer thread\" (TID:0x1339088, sys_thread_t:0xd1c670, Win32ID:0x145, state:CW) prio=2\n    \"main\" (TID:0x13390b0, sys_thread_t:0xd1b8b0, Win32ID:0x14f, state:CW) prio=5\nMonitor Cache Dump:\n    threads.Account@133D130\/1429100: owner (0x7ffd9000, 1 entry)\n    threads.Account@133D148\/14290B8: owner (0x7ffda000, 1 entry)\nRegistered Monitor Dump:\n    SymcJIT Method Monitor: &lt;unowned&gt;\n    SymcJIT Method List Monitor: &lt;unowned&gt;\n    SymcJIT Lock: &lt;unowned&gt;\n    Thread queue lock: &lt;unowned&gt;\n        Waiters: 1\n    Name and type hash table lock: &lt;unowned&gt;\n    String intern lock: &lt;unowned&gt;\n    JNI pinning lock: &lt;unowned&gt;\n    JNI global reference lock: &lt;unowned&gt;\n    BinClass lock: &lt;unowned&gt;\n    Class loading lock: &lt;unowned&gt;\n    Java stack lock: &lt;unowned&gt;\n    Code rewrite lock: &lt;unowned&gt;\n    Heap lock: &lt;unowned&gt;\n    Has finalization queue lock: &lt;unowned&gt;\n    Finalize me queue lock: &lt;unowned&gt;\n        Waiters: 1\n    Monitor registry: owner (0x7ffd8000, 1 entry)<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s a quick synopsis of a Java Stack Trace:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The possible thread states are:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>R<\/strong>&nbsp;&#8212; Running or runnable thread<\/li><li><strong>S<\/strong>&nbsp;&#8212; Suspended thread<\/li><li><strong>CW<\/strong>&nbsp;&#8212; Thread waiting on a condition variable<\/li><li><strong>MW<\/strong>&nbsp;&#8212; Thread waiting on a monitor lock<\/li><li><strong>MS<\/strong>&nbsp;&#8212; Thread suspended waiting on a monitor lock<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">and you&#8217;ll note that Thread A and Thread B are both in state:&nbsp;<strong>MW<\/strong>&nbsp;&#8212;&nbsp;<em>monitor wait<\/em>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The thread stack trace shows where the threads are &#8212; both threads are at the same point in their respective code &#8212; both are attempting to acquire a lock on their respective&nbsp;<strong>m_to<\/strong>&nbsp;objects.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\"><p><em><strong>Can you explain what&#8217;s happening? Where is the problem? How can we solve it?<\/strong><\/em><\/p><\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">As you can see, when you&#8217;re dealing with multiple threads, you have to be aware of the possibility of deadlock, and try to avoid that.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Starvation_Livelock\"><\/span>Starvation &amp; Livelock<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">There are also potentially problematic conditions that you need to be aware of when designing or implementing multi-threaded applications.&nbsp; These conditions are known as&nbsp;<em><strong>starvation<\/strong><\/em>&nbsp;and&nbsp;<strong><em>livelock<\/em><\/strong>:<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Starvation\"><\/span>Starvation<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\"><em><strong>Starvation<\/strong><\/em>&nbsp;describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by &#8220;greedy&#8221; threads.&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Livelock\"><\/span>Livelock<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">A thread often acts in response to the action of another thread. If the other thread&#8217;s action is also a response to the action of another thread, then <em><strong>livelock<\/strong><\/em> may result. As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked \u2014 they are simply too busy responding to each other to resume work.&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is analogous to two people attempting to pass each other in a corridor: Larry moves to his left to let Curly pass, while Curly moves to his right to let Larry pass. Seeing that they are still blocking each other, Larry moves to his right, while Curly moves to his left. They&#8217;re still blocking each other, so&#8230;<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Thread_Coordination\"><\/span>Thread Coordination<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Why Do We Need Thread Coordination?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Threads are often interdependent. That is, one thread may depend on another thread (or several other threads) to perform an operation or service a request.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">A common problem is when a user requests a program to do something (such as a time-consuming calculation, or a complex database query, or some other process that takes time). Typically, the user interacts with the graphical user interface provided by the Java program. If the requested operation were to be performed in the same thread as the user interface, the user interface would become non-responsive. (I&#8217;m sure you&#8217;ve encountered programs that have done this to you!).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In Java, it is easy to create a thread and do the time-consuming operation in that thread, thereby freeing up the user interface thread to remain responsive.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">But this introduces another problem: Once the long-running operation has completed, how does it notify the user interface thread that the work is done, so that the appropriate updates may be made to the user interface?<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is just one example of how two threads have a need to coordinate with each other.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"ProducerConsumer_Relationships\"><\/span>Producer\/Consumer Relationships<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A&nbsp;<em><strong>producer\/consumer relationship<\/strong><\/em>&nbsp;is a very common relationship among threads. In this kind of a relationship, the&nbsp;<strong><em>Producer<\/em><\/strong>&nbsp;thread is responsible for producing something (in this case, work), and the&nbsp;<strong><em>Consumer<\/em><\/strong>&nbsp;thread is responsible for consuming it (in this case performing the work). Note:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The&nbsp;<strong><em>Producer<\/em><\/strong>&nbsp;produces something and notifies the&nbsp;<strong><em>Consumer<\/em><\/strong>&nbsp;that it is available.<\/li><li>The&nbsp;<strong>Consumer<\/strong>&nbsp;can&#8217;t do anything until it&#8217;s given something to consume, so it must wait until there is something available.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The typical pseudo-code for a&nbsp;<strong><em>Producer<\/em><\/strong>&nbsp;is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">enter synchronized code\n  produce data\n  notify consumer\nleave synchronized code<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">while the typical pseudo-code for a&nbsp;<strong><em>Consumer<\/em><\/strong>&nbsp;is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">enter synchronized code\n  while there is no data available\n    wait\n  consume data\nleave synchronized code<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">In theory, the&nbsp;<strong><em>Producer<\/em><\/strong>&nbsp;could produce things as fast as it can, regardless of whether the&nbsp;<strong><em>Consumer<\/em><\/strong>&nbsp;can keep up. In the real world, to avoid running out of resources, the&nbsp;<strong><em>Producer<\/em><\/strong>&nbsp;shouldn&#8217;t produce anything at a rate the the&nbsp;<strong><em>Consumer<\/em><\/strong>&nbsp;can&#8217;t match. For example, it is common for data to be passed from a&nbsp;<strong><em>Producer<\/em><\/strong>&nbsp;to a&nbsp;<strong><em>Consumer<\/em><\/strong>&nbsp;by means of a shared buffer. If the buffer fills up, then the&nbsp;<strong><em>Producer<\/em><\/strong>&nbsp;shouldn&#8217;t attempt to continue using that buffer, but should wait for room to become available in the buffer.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Conditions\"><\/span>Conditions<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">A Consumer thread is typically waiting on some&nbsp;<em><strong>condition<\/strong><\/em>&nbsp;to become true. While the condition remains false, the Consumer thread must continue to wait.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<em><strong>waiting<\/strong><\/em>&nbsp;is performed by calling the&nbsp;<strong>wait()<\/strong>&nbsp;method, and the <em><strong>notification<\/strong><\/em> is performed by calling the&nbsp;<strong>notify()<\/strong>&nbsp;method.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Every class has access to these methods, since they are implemented in the Object class &#8212; the ultimate global superclass.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each of these methods&nbsp;<em><strong>must<\/strong><\/em>&nbsp;be called from within a&nbsp;<strong>synchronized<\/strong>&nbsp;block.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_wait_Method\"><\/span>The wait() Method<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public final void wait() throws InterruptedException<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Waits to be notified by another thread of a change in this object. The current thread must own this object&#8217;s monitor.&nbsp;<em><strong>The thread releases ownership of this monitor<\/strong><\/em>&nbsp;and waits until another thread notifies threads waiting on this object&#8217;s monitor to wake up either through a call to the&nbsp;<strong>notify<\/strong>&nbsp;method or the&nbsp;<strong>notifyAll<\/strong>&nbsp;method.&nbsp;<em><strong>The thread then waits until it can re-obtain ownership of the monitor<\/strong>&nbsp;<\/em>and resumes execution.&nbsp;<strong>This method should only be called by a thread that is the owner of this object&#8217;s monitor.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<strong>wait()<\/strong>&nbsp;method:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Throws&nbsp;<strong>IllegalMonitorStateException<\/strong>&nbsp;if the current thread is not the owner of the object&#8217;s monitor.<\/li><li>Throws&nbsp;<strong>InterruptedException<\/strong>&nbsp;if another thread has interrupted this thread.<\/li><\/ul>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_notify_Method\"><\/span>The notify() Method<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public final void notify()<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Wakes up a single thread that is waiting on this object&#8217;s monitor. A thread waits on an object&#8217;s monitor by calling one of the wait methods.&nbsp;<strong>This method should only be called by a thread that is the owner of this object&#8217;s monitor.&nbsp;<\/strong>A thread becomes the owner of the object&#8217;s monitor in one of three ways:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>By executing a&nbsp;<strong>synchronized<\/strong>&nbsp;instance method of that object.<\/li><li>By executing the body of a&nbsp;<strong>synchronized<\/strong>&nbsp;statement that synchronizes on the object.<\/li><li>For objects of type&nbsp;<strong>Class<\/strong>, by executing a&nbsp;<strong>synchronized<\/strong>&nbsp;static method of that class.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Only one thread at a time can own an object&#8217;s monitor.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<strong>notify()<\/strong>&nbsp;method:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Throws&nbsp;<strong>IllegalMonitorStateException<\/strong>&nbsp;if the current thread is not the owner of this object&#8217;s monitor.<\/li><\/ul>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Other_wait_Methods\"><\/span>Other wait() Methods<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">There are also two forms of the&nbsp;<strong>wait()<\/strong>&nbsp;method that may be used if the thread is not willing to wait forever:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public final void wait(long timeout)&nbsp;<br>&nbsp;&nbsp;&nbsp; throws InterruptedException<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Waits to be notified by another thread of a change in this object. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Another thread notifies threads waiting on this object&#8217;s monitor to wake up either through a call to the notify method or the&nbsp;<strong>notifyAll<\/strong>&nbsp;method.<\/li><li>The timeout period, specified by the timeout argument in milliseconds, has elapsed. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>This method should only be called by a thread that is the owner of this object&#8217;s monitor.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Parameters:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>timeout<\/strong>&nbsp;&#8211; the maximum time to wait in milliseconds.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This&nbsp;<strong>wait()<\/strong>&nbsp;method:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Throws&nbsp;<strong>IllegalArgumentException<\/strong>&nbsp;if the value of&nbsp;<strong>timeout<\/strong>&nbsp;is negative.<\/li><li>Throws&nbsp;<strong>IllegalMonitorStateException<\/strong>&nbsp;if the current thread is not the owner of the object&#8217;s monitor.<\/li><li>Throws&nbsp;<strong>InterruptedException<\/strong>&nbsp;if another thread has interrupted this thread.<\/li><\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public final void wait(long timeout, int nanos)&nbsp;<br>&nbsp;&nbsp;&nbsp; throws InterruptedException<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Waits to be notified by another thread of a change in this object. This method is similar to the wait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. The thread releases ownership of this monitor and waits until either of the following two conditions has occurred:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Another thread notifies threads waiting on this object&#8217;s monitor to wake up either through a call to the notify method or the notifyAll method.<\/li><li>The timeout period, specified by timeout milliseconds plus nanos nanoseconds arguments, has elapsed.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The thread then waits until it can re-obtain ownership of the monitor and resumes execution T<strong>his method should only be called by a thread that is the owner of this object&#8217;s monitor<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Parameters:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>timeout<\/strong>&nbsp;&#8211; the maximum time to wait in milliseconds.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>nanos<\/strong>&nbsp;&#8211; additional time, in nanoseconds range 0-999999.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This wait method:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Throws&nbsp;<strong>IllegalArgumentException<\/strong>&nbsp;if the value of timeout is negative or the value of&nbsp;<strong>nanos<\/strong>&nbsp;is not in the range 0-999999.<\/li><li>Throws&nbsp;<strong>IllegalMonitorStateException<\/strong>&nbsp;if the current thread is not the owner of this object&#8217;s monitor.<\/li><li>Throws&nbsp;<strong>InterruptedException<\/strong>&nbsp;if another thread has interrupted this thread.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Throws:&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>IllegalMonitorStateException<\/strong>&nbsp;if the current thread is not the owner of this object&#8217;s monitor.<\/p>\n\n\n\n<h5 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"The_notifyAll_Method\"><\/span>The notifyAll() Method<span class=\"ez-toc-section-end\"><\/span><\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">There are occasions when we&#8217;d like to have a number of threads waiting on a monitor. For example, there might be a number of threads capable of doing work as a&nbsp;<strong><em>Consumer<\/em><\/strong>. When there is work available, if the&nbsp;<strong><em>Producer<\/em><\/strong>&nbsp;calls&nbsp;<strong>notifyAll()<\/strong>, it causes all the threads waiting on that monitor to return from their&nbsp;<strong>wait()<\/strong>:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>public final void notifyAll()<\/strong><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Wakes up all threads that are waiting on this object&#8217;s monitor. A thread waits on an object&#8217;s monitor by calling one of the wait methods.&nbsp;<strong>This method should only be called by a thread that is the owner of this object&#8217;s monitor.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The&nbsp;<strong>notifyAll()<\/strong>&nbsp;method:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Throws&nbsp;<strong>IllegalMonitorStateException<\/strong>&nbsp;if the current thread is not the owner of this object&#8217;s monitor.<\/li><\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">In general,&nbsp;<strong>notifyAll()<\/strong>&nbsp;tends to be safer than relying on&nbsp;<strong>notify()<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In general,&nbsp;<strong>notifyAll()<\/strong>&nbsp;tends to be safer than relying on&nbsp;<strong>notify()<\/strong>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"A_ProducerConsumer_Example\"><\/span>A Producer\/Consumer Example<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example of a&nbsp;<strong>Producer<\/strong>&nbsp;and a&nbsp;<strong>Consumer<\/strong>&nbsp;class, with a <strong>SharedBuffer<\/strong> class that provides the necessary coordination between the two threads:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.io.IOException;\nimport java.util.ArrayList;\nimport java.util.List;\n\n\n\/**\n *  This is a Producer thread that supplies strings\n *  to a Consumer thread.  It reads a line from System.in\n *  and passes it to the Consumer through a SharedBuffer,\n *  until the end of stream occurs.\n *\/\npublic class Producer extends Thread\n{\n  public static void main(String&#x5B;] args)\n  {\n    \/\/ Create a shared buffer\n    SharedBuffer buffer = new SharedBuffer();\n    \/\/ Create and start a consumer thread\n    Consumer consumer = new Consumer(buffer);\n    consumer.start();\n    \/\/ Create and start a Producer thread\n    Producer producer = new Producer(buffer);\n    producer.start();\n  }\n  \n  Producer(SharedBuffer buffer)\n  {\n    super(&quot;Producer&quot;);\n    m_buffer = buffer;\n  }\n  \n  public void run()\n  {\n    \/\/ Connect up to System.in\n    BufferedReader reader = new BufferedReader(\n      new InputStreamReader(System.in)\n      );\n    \n    try\n    {\n      \/\/ Loop, asking for input from the user until EOF\n      while (true)\n      {\n        String line = reader.readLine();\n        if (line == null)\n          break;      \/\/ End of input\n        m_buffer.putData(line);\n      }\n    }\n    catch (IOException e)\n    {\n      e.printStackTrace();\n    }\n    \n    System.out.println(&quot;Done with input: Signalling to Consumer&quot;);\n    m_buffer.putData(null);\n  }\n  \n  \/\/\/ Private data \/\/\/\n  private SharedBuffer m_buffer;\n}\n\n\/**\n *  This is a Consumer thread that waits for input from\n *  the Producer, supplied through a SharedBuffer.  It\n *  accepts the string passed, reverses it, and prints out\n *  the result.  When it encounters a null string, the thread\n *  exits.\n *\/\nclass Consumer extends Thread\n{\n  Consumer(SharedBuffer buffer)\n  {\n    super(&quot;Consumer&quot;);\n    m_buffer = buffer;\n  }\n  \n  public void run()\n  {\n    while (true)\n    {\n      String line = m_buffer.getData();\n      if (line == null)\n        break;\n      \/\/ Reverse the line and print it out\n      line = reverse(line);\n      System.out.println(line);\n    }\n    \n    System.out.println(&quot;Consumer thread exiting...&quot;);\n  }\n  \n  private String reverse(String string)\n  {\n    StringBuffer buffer = new StringBuffer(string);\n    return buffer.reverse().toString();\n  }\n  \n  \/\/\/\/ Private data \/\/\/\/\n  private SharedBuffer m_buffer;\n}\n\n\/**\n *  This is a SharedBuffer class to which the Producer puts\n *  data, and from which the Consumer retrieves it.\n *  It contains the necessary thread coordination code to\n *  ensure that the Producer and Consumer work together properly.\n *\/\nclass SharedBuffer\n{\n  static final int RESOURCE_LIMIT = 10;\n  \n  boolean isFull()\n  {\n    return m_data.size() &gt; RESOURCE_LIMIT;\n  }\n  \n  boolean isEmpty()\n  {\n    return m_data.size() &lt;= 0;\n  }\n  \n  synchronized void putData(String s)\n  {\n    while ( isFull() )  \/\/ Wait until there&#039;s room\n    {\n      try\n      {\n        wait();\n      }\n      catch (InterruptedException e)\n      {\n        \/\/ Ignore\n      }\n    }\n    \n    m_data.add(s);   \/\/ To the end of the FIFO list\n    \n    notify();       \/\/ Notify any waiter\n  }\n  \n  synchronized String getData()\n  {\n    while ( isEmpty() ) \/\/ Wait until there&#039;s data available\n    {\n      try\n      {\n        wait();\n      }\n      catch (InterruptedException e)\n      {\n        \/\/ Ignore\n      }\n    }\n    \n    String data = (String)(m_data.get(0)); \/\/ Get first element\n    if (data != null)\n      m_data.remove(data);     \/\/ and remove it from the List\n    \n    notify();       \/\/ Notify any waiter\n    \n    return data;\n  }\n  \n  \/\/\/\/ Private data \/\/\/\/\n  \n  \/\/ A list of strings.\n  private List&lt;String&gt; m_data = new ArrayList&lt;String&gt;();\n  private boolean m_done = false;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s a simple example of one run of this program:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Hello!\n!olleH\nHow are you?\n?uoy era woH\nNice talking to you!\n!uoy ot gniklat eciN\nGoodbye\neybdooG\nDone with input: Signalling to Consumer\nConsumer thread exiting...<\/strong><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Communication_Between_Threads\"><\/span>Communication Between Threads<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"Using_Pipes_to_Communicate_between_Threads\"><\/span>Using Pipes to Communicate between Threads<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Sometimes the communication requirements between threads is quite simple. Take, for example, the case where the producer creates a stream of characters and the consumer reads and processes that stream.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Java has a convenient set of&nbsp;<em>Piped<\/em>&nbsp;classes that provide the support for just such a circumstance:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>PipedReader<\/strong>&nbsp;and&nbsp;<strong>PipedWriter<\/strong>, for text data<\/li><li><strong>PipedInputStream<\/strong>&nbsp;and&nbsp;<strong>PipedOutputStream<\/strong>, for non-text data<\/li><\/ul>\n\n\n\n<h4 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"An_Example\"><\/span>An Example<span class=\"ez-toc-section-end\"><\/span><\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s modify the previous Producer\/Consumer example to use&nbsp;<strong>Piped<\/strong>&nbsp;classes for coordination:<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: java; auto-links: false; title: ; quick-code: false; notranslate\" title=\"\">\npackage threads;\n\nimport java.io.BufferedReader;\nimport java.io.InputStreamReader;\nimport java.io.IOException;\nimport java.io.PipedReader;\nimport java.io.PipedWriter;\nimport java.io.PrintWriter;\n\n\/**\n *  This is a PipedProducer thread that supplies strings\n *  to a PipedConsumer thread.  It reads a line from System.in\n *  and passes it to the PipedConsumer through a SharedBuffer,\n *  until the end of stream occurs.\n *\/\npublic class PipedProducer extends Thread\n{\n  public static void main(String&#x5B;] args)\n  {\n    try\n    {\n      \/\/ Create the input and output pipes and hook them up\n      PipedWriter writer = new PipedWriter();\n      PipedReader reader = new PipedReader(writer);\n      \/\/ Create and start a consumer thread\n      PipedConsumer consumer = new PipedConsumer(reader);\n      consumer.start();\n      \/\/ Create and start a PipedProducer thread\n      PipedProducer producer = new PipedProducer(writer);\n      producer.start();\n    }\n    catch (IOException e)\n    {\n      e.printStackTrace();\n    }\n  }\n  \n  PipedProducer(PipedWriter writer)\n  {\n    super(&quot;Producer&quot;);\n    m_writer = new PrintWriter(writer);\n  }\n  \n  public void run()\n  {\n    \/\/ Connect up to System.in\n    BufferedReader reader = new BufferedReader(\n      new InputStreamReader(System.in)\n      );\n    \n    try\n    {\n      \/\/ Loop, asking for input from the user until EOF\n      while (true)\n      {\n        String line = reader.readLine();\n        if (line == null)\n          break;      \/\/ End of input\n        m_writer.println(line);\n      }\n    }\n    catch (IOException e)\n    {\n      e.printStackTrace();\n    }\n    \n    System.out.println(&quot;Done with input: Closing pipe&quot;);\n    m_writer.close();\n  }\n  \n  \/\/\/ Private data \/\/\/\n  private PrintWriter m_writer;\n}\n\n\/**\n *  This is a PipedConsumer thread that waits for input from\n *  the PipedProducer, supplied through a SharedBuffer.  It\n *  accepts the string passed, reverses it, and prints out\n *  the result.  When it encounters a null string, the thread\n *  exits.\n *\/\nclass PipedConsumer extends Thread\n{\n  PipedConsumer(PipedReader reader)\n  {\n    super(&quot;Consumer&quot;);\n    m_reader = new BufferedReader(reader);\n  }\n  \n  public void run()\n  {\n    try\n    {\n      while (true)\n      {\n        String line = m_reader.readLine();\n        if (line == null)\n          break;\n        \/\/ Reverse the line and print it out\n        line = reverse(line);\n        System.out.println(line);\n      }\n    }\n    catch (IOException e)\n    {\n      e.printStackTrace();\n    }\n    \n    System.out.println(&quot;Consumer thread exiting...&quot;);\n  }\n  \n  private String reverse(String string)\n  {\n    StringBuffer buffer = new StringBuffer(string);\n    return buffer.reverse().toString();\n  }\n  \n  \/\/\/\/ Private data \/\/\/\/\n  private BufferedReader m_reader;\n}\n<\/pre><\/div>\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s an example of the output from one run of this program:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"><strong>Hello there!\n!ereht olleH\nNice to see you!\n!uoy ees ot eciN\nGotta go!\n!og attoG\nDone with input: Closing pipe\nConsumer thread exiting...<\/strong><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Monitors, Synchronization &amp; Deadlocks Why do we need Synchronization? Let&#8217;s look at an example of a Java program where we ignore the problem, and see what trouble we get into. Example: A Steam Boiler The following program is a simple emulation of a steam boiler. The boiler has a number of burners (this is a [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"parent":252,"menu_order":0,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_eb_attr":"","ocean_front_end_style_editor":"no","ocean_post_layout":"left-sidebar","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"ocs-course-topics-sidebar","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","footnotes":""},"class_list":["post-280","page","type-page","status-publish","hentry","entry"],"_links":{"self":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/280","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/comments?post=280"}],"version-history":[{"count":21,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/280\/revisions"}],"predecessor-version":[{"id":378,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/280\/revisions\/378"}],"up":[{"embeddable":true,"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/pages\/252"}],"wp:attachment":[{"href":"https:\/\/bhiggs.x10hosting.com\/HighOctaneJava\/wp-json\/wp\/v2\/media?parent=280"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}