View RSS Feed

My Java Tips

Java Threads - synchronized

Rate this Entry
by , 10-28-2011 at 08:27 PM (1268 Views)
In multithreaded environment, data may be corrupted. A was to prevent this is to prevent the interruption of critical regions.


You have to fidn the critical region in your code which you think should be accessed by one thread at a time. Java's synchronized is used to ensure that only one thread is in a critical region at once. When the thread enters a synchronized code block, it locks on that region and no other thread can enter the critical region as long as the lock is released. If a thread tries to enter and the code is already locked, the thread has to wait for the other thread to leave the critical region. An example is presented below:
Java Code:
      public void run()
        {
          int i=0;
          int tmp;       /*new*/
          for(;;)
            {
              for(i=0;i<1000;i++)
                {
                    synchronized (this)  /*new*/
                    {
                      num=num+10;
                      num=num-10;
                    }
                }

              try {Thread.sleep(10000);}
              catch (InterruptedException e ) {}
              synchronized (this)                    /*new*/
              {tmp=num;}                             /*new*/
              System.out.println(Thread.currentThread().getName()+
                         " sees the number: " + tmp); /*new*/
            }
        }

Submit "Java Threads - synchronized" to Facebook Submit "Java Threads - synchronized" to Digg Submit "Java Threads - synchronized" to del.icio.us Submit "Java Threads - synchronized" to StumbleUpon Submit "Java Threads - synchronized" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments