View RSS Feed

My Java Tips

Java Threads - synchronized

Rate this Entry
by , 10-28-2011 at 08:27 PM (1661 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*/
                    synchronized (this)  /*new*/

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

Submit "Java Threads - synchronized" to Facebook Submit "Java Threads - synchronized" to Digg Submit "Java Threads - synchronized" to Submit "Java Threads - synchronized" to StumbleUpon Submit "Java Threads - synchronized" to Google

Tags: None Add / Edit Tags
Java SE