All ITKnowledge Source Code Search Tips Advanced Search |

| Mastering Java Threads by Marc Adler and David Herst DDC Publishing, Inc. ISBN: 1562438425 Pub Date: 05/01/99

Search this book:

Previous | Table of Contents | Next

#### Critical Sections

A section of code to which only one thread is allowed access is called a critical section. True multiprocessing systems recognize the need for critical sections and implement them within the operating system. For example, the Win32 API has the EnterCriticalSection and LeaveCriticalSection functions which allow you to surround code that is intended for access by one thread at a time.

#### Synchronized

Java implements critical sections through the use of the keyword synchronized. You can mark any block of code as being a synchronized block, although this keyword is generally used to mark an entire method within a class.

Below is the StockApp rewritten to take advantage of monitors:

    import java.applet.*;

    class StockApp extends Applet implements Runnable

    {

      public String m_szStockName;

      public double m_dblStockPrice;

      public boolean m_bStockPending = false;

      public PollingThread m_ReutersPollingThread

          new PollingThread(“Reuters”);

      public PollingThread m_TeleratePollingThread =

          new PollingThread(“Telerate”);

      public void start ()

      {

        m_ReutersPollingThread.start();

        m_TeleratePollingThread.start();

      }

      public void run()

      {

        while (m_ReutersPollingThread != null &&

               m_TeleratePollingThread != null)

        {

          ProcessPendingStock();

        }

      }

      public synchronized void InsertPendingStock (

               String sStockName, double dblPrice)

      {

         while (m_bStockPending == true)

         {

         try

         {

            wait();

         } catch (InterruptedException e)

         {

         }

       }

        m_szStockName = sStockName;

        m_dblStockPrice = dblPrice;

        m_bStockPending = false;

        notifyAll();

      }

      public synchronized void ProcessPendingStock ()

      {

        /*

           Insert the stock info into a database. . . .

        */

        while (m_bStockPending == false)

        {

          try

          {

             wait();

          } catch (InterruptedException e)

          {

          }

        }

        m_bStockPending = false;

        notifyAll();

      }

      class PollingThread extends Thread

      {

         public PollingThread (String szName)

         {

           super(szName);

           /*

             We can open a server connection based on the thread name

           */

        }

        public void run()

        {

          String sStockName;

          double dblPrice;

          for (;;)

          {

            /*

               Read the stock info from the server. . . .

               We block until we get a stock.

            */

            try

            {

              Thread.sleep(1000);

            } catch (InterruptedException e)

            {

            }

            /*

            if (we got a response from the server)

            {

               read the stock name/price into local variables

               sStockName and dblPrice

            */

               InsertPendingStock(sStockName, dblPrice);

             /*

             }

             */

           }

         }

      }

    }

### The Scope of a Lock

The scope of a lock is the period of time between when a lock is acquired and when it is released. If an entire method is synchronized, the lock is said to have method scope.

Note the following points regarding the scope of a lock.

  • Try to keep the scope of a lock as short as possible.
  • Do not keep other threads locked out of code for long periods of time.

#### Object & Class Locks

Each instance of an Object in Java has a lock associated with it. When an Object is created, the lock is disabled. The synchronized keyword is used to define the scope when the lock on an object will be enabled.

When an entire method is synchronized, the Object with which the method is associated is locked for the scope of that method. For instance, in the example in the previous section, the instance of the StockApp object is locked when ProcessPendingStock() is called.

A lock is associated with an instance of an Object. Thus, if you have two separate instances of an Object, your application can execute a synchronized method multiple times simultaneously, once for each instance.

Class Locks

What happens if a static method is synchronized? As you should know, in Java there is no instance of an Object that is associated with a static method. Thus, there is no instance of an Object to lock. In this case, Java locks something that is referred to as a class lock. Internally, the class lock is really the lock on the Java Object which is used to represent the class itself.

A class lock is distinct from the object lock. You can hold and release a lock on the class independently from the lock on an object.

| If an entire method is synchronized, the lock is said to have method scope.

### Synchronized Blocks

The synchronized keyword cannot only be used to modify an entire method, but it can also be used to enclose a block of code within a non-synchronized method. The syntax of a synchronized block is as follows:

        synchronized (  Expression ) Block

If the type of Expression is not a reference to an Object, a compile-time error will occur. For example, it cannot be an expression such as the following:

        synchronized (1+2)

#### Block Execution

You should allow the non-null value of the Expression be V. The executing thread locks the lock associated with V. Then the Block is executed. If execution of the Block completes normally, the lock is unlocked and the synchronized statement completes normally. If execution of the Block completes abruptly for any reason, the lock is unlocked and the synchronized statement then completes abruptly for the same reason.

Acquiring the lock associated with an object does not in itself prevent other threads from accessing fields of the object or invoking unsynchronized methods on the object. Other threads can also use synchronized methods or the synchronized statement in a conventional manner to achieve mutual exclusion.

#### Synchronized Blocks vs Methods

Which kind of locking method should you use? Synchronizing 1) a block or 2) an entire method? Other than the issues listed below, personal preference dictates which variant of locking to use.

Pros & Cons

Synchronizing a method offers pros and cons:

  • Pro: is easy to use
  • Con: may result in a lock scope that is too large

  | Synchronizing a block may be expensive if you acquire and release a lock, only to reacquire and re-release it a few lines later. Locks are expensive to obtain and release.

Previous | Table of Contents | Next

Copyright © DDC Publishing

Products | Contact Us | About Us | Privacy | Ad Info | Home Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.