A Fixed Steam Boiler
Home ] Up ] A Steam Boiler ] Race Conditions ] Monitors ] Synchronization ] [ A Fixed Steam Boiler ] Deadlock ] Starvation & Livelock ]

 

 

Now, let's go back to our SteamBoiler class, and change the burn() method in class Burner to:

private void burn()
{
    synchronized (m_boiler)
    {
        if (m_boiler.getPressure() < 
                   SteamBoiler.PRESSURE_LIMIT - PRESSURE_INCREMENT)
        {
            // Wait to simulate delay
            try
            {
                sleep(100);
            }
            catch (InterruptedException e)
            {
                // Ignore
            }
                
            m_boiler.setPressure( m_boiler.getPressure() + 
                                  PRESSURE_INCREMENT );
        }
    }
}

The only change is to surround the code with a synchronized statement, specifying the instance of SteamBoiler as the object on which to synchronize. 

Why did I choose to synchronize on the instance of SteamBoiler? Why did I not simply make the burn() method synchronized?

To show it works, here's the fixed SteamBoilerApplet:

You do not have Java enabled. Please do so!
Here are the sources for this applet:

 

The page was last updated February 19, 2008