Results 1 to 11 of 11
Like Tree2Likes
  • 2 Post By gimbal2

Thread: Synchronized Blocks in Static Methods Confusion

  1. #1
    MasterChief is offline Member
    Join Date
    Jul 2014
    Posts
    3
    Rep Power
    0

    Default Synchronized Blocks in Static Methods Confusion

    Hi guys,
    I was reading this: Java Synchronized Blocks

    As I'm trying to get my head around the synchronized keyword.

    My query is based on some simple example code below.

    Query: If threadOne executes before threadTwo and invokes the "add" method which synchronizes on the class object will thead2 continue to be blocked from updating both the
    instanceVariableInt and the class variable someOtherInt until the intrinsic lock on Test.class has been released? (threadOne has left the synchronized statement code)

    Java Code:
    public class Test {
    
    	private static int value = 10;
    	
    	private static int someOtherInt = 50;
    	private int instanceVariableInt = 100;
    
    	public int add(int digit){
    		synchronized(Test.class){
    			value =+ digit;
    		}
    
    		return value;
    	}
    
    	public void printName(){
    		System.out.println(Test.class.getName());
    	}
    	
    	public void doSomething(){
    		//Update instance variable
    		instanceVariableInt += 50;
    		
    		//Update some other class variable
    		someOtherInt = 70;
    	}
    
    	public static void main(String[] args) {
    		final Test threadOne = new Test();
    		final Test threadTwo = new Test();
    
    		new Thread(new Runnable() {
    			public void run() {
    				threadOne.add(10);
    			}
    		}).start();
    
    		new Thread(new Runnable() {
    			public void run() {
    				threadTwo.printName();
    				threadTwo.doSomething();
    			}
    		}).start();
    	}
    }

    Thanks :)

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,411
    Rep Power
    5

    Default Re: Synchronized Blocks in Static Methods Confusion

    Other than main, you have no static methods. The way it is written, only the add method will block another method from continuing with that method until the object lock is released. The two variables you mentioned may be updated by other means by other threads at any time since they are not subject to any synchronization.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    MasterChief is offline Member
    Join Date
    Jul 2014
    Posts
    3
    Rep Power
    0

    Default Re: Synchronized Blocks in Static Methods Confusion

    Thanks for the quick response Jim.

    So when synchronization is performed on the class itself, it does not prevent other class variables from being updated during the period when a thread has lock on the class?


    I was reading this article and just had another related question to the synchronized statement.
    Intrinsic Locks and Synchronization (The Java™ Tutorials > Essential Classes > Concurrency)


    Synchronized Statements

    Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:

    Java Code:
    public void addName(String name) {
        synchronized(this) {
            lastName = name;
            nameCount++;
        }
        nameList.add(name);
    }
    In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects' methods. (Invoking other objects' methods from synchronized code can create problems that are described in the section on Liveness.) Without synchronized statements, there would have to be a separate, unsynchronized method for the sole purpose of invoking nameList.add.
    Question: If an object is used to call another method within a synchronized block, is there implicitly a lock on that object? From what I read above, I interpreted that if nameList.add was inside that synchronized block then there would be a lock on namelist and other methods would not be able to update it until that lock had been released. Is this interpretation correct?

    Cheers,

  4. #4
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,411
    Rep Power
    5

    Default Re: Synchronized Blocks in Static Methods Confusion

    Quote Originally Posted by MasterChief View Post
    So when synchronization is performed on the class itself, it does not prevent other class variables from being updated during the period when a thread has lock on the class?
    Correct (except that threads don't have locks on the class, only on methods and synchronized blocks). Synchronization only affects simultaneous access to fields within the synchronized block when using the same lock (monitor).

    Quote Originally Posted by MasterChief View Post
    Question: If an object is used to call another method within a synchronized block, is there implicitly a lock on that object? From what I read above, I interpreted that if nameList.add was inside that synchronized block then there would be a lock on namelist and other methods would not be able to update it until that lock had been released. Is this interpretation correct?
    Locks only apply to synchronization. If an instance method is synchronized on this, then that instance may still access other methods as long as they are not synchronized or not synchronized on this.

    Some of this may not be intuitive and my answers also depend on understanding what you are asking. I recommend you try some examples using two threads (perhaps main and one other). Use different or same locks on different methods or synchronized blocks. If the code does not do what you expect, then someone on this forum should be able to explain why. It is essential to try examples to ensure full understanding.

    Regards,
    Jim
    Last edited by jim829; 07-15-2014 at 05:20 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  5. #5
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,705
    Rep Power
    5

    Default Re: Synchronized Blocks in Static Methods Confusion

    Yay Paint Creativity time! Hi, I'm Gimby and I suck at Paint.

    Lets illustrate a basic sketch of what you want to achieve and what you want to prevent when it comes to thread synchronization. This is a simple world in which there is a wall with a closed door and an open door; that wall is all that stands between the nasty outdoors and the object properties.

    Synchronized Blocks in Static Methods Confusion-thread_example.png

    That door has only one key; each thread is allowed through one at a time and must pass the key on to the next thread waiting in line. The world is sane, each thread manipulates the object all privately and alone behind that wall. The other threads cannot interfere.

    Synchronized Blocks in Static Methods Confusion-thread_example2.png

    Until one day there is this evil thread that sees the open door and just decides to run through it without waiting for its turn to get the key. There is chaos, there are now two threads that can pull on the levers and push the buttons of the object at the same time. Before long, the object grinds to a halt with lots of black smoke. If only that evil thread had waited for its turn to get the key.

    Synchronized Blocks in Static Methods Confusion-thread_example3.png

    The end! (good god I hope this looks okay)
    jim829 and SurfMan like this.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,817
    Rep Power
    19

    Default Re: Synchronized Blocks in Static Methods Confusion

    A masterpiece!
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,411
    Rep Power
    5

    Default Re: Synchronized Blocks in Static Methods Confusion

    Hi, my name is Thread! See Thread run. Run Thread run! Watch Thread muck things up.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  8. #8
    MasterChief is offline Member
    Join Date
    Jul 2014
    Posts
    3
    Rep Power
    0

    Default Re: Synchronized Blocks in Static Methods Confusion

    Hi Guys,
    Thanks a heap for the help! I understand how it all works out now ( I think). Great diagram too!

    Locks only apply to synchronization. If an instance method is synchronized on this, then that instance may still access other methods as long as they are not synchronized or not synchronized on this.
    So each thread needs the intrinsic lock which it gets from the monitor to execute synchronized code and the reason in the quote above why instance methods may still access other methods as long as they are not synchronized or synchronized on this is that ONLY one thread can have the intrinsic lock so the invocations to other methods which are synchronized will be blocked until they can get a hold of that intrinsic lock themselves in order to execute the code. Is this understanding now correct?

    One last curious question if you have 2 synchronized methods, but one synchronizes on this and the other synchronizes on the Class itself, are there 2 intrinsic locks which will allow an instance of the class to access both methods simultaneously?

    Cheers :)

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,411
    Rep Power
    5

    Default Re: Synchronized Blocks in Static Methods Confusion

    Quote Originally Posted by MasterChief View Post
    Is this understanding now correct?
    Yes!
    One last curious question if you have 2 synchronized methods, but one synchronizes on this and the other synchronizes on the Class itself, are there 2 intrinsic locks which will allow an instance of the class to access both methods simultaneously?
    Why not try it yourself. For a class Foo, sync one block on this and one block on Foo.class and see what happens.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  10. #10
    SurfMan's Avatar
    SurfMan is offline Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    929
    Rep Power
    2

    Default Re: Synchronized Blocks in Static Methods Confusion

    Quote Originally Posted by gimbal2 View Post
    Yay Paint Creativity time! Hi, I'm Gimby and I suck at Paint.
    I am going to print this, and hang it at the coffee machine.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2™ © 2013

  11. #11
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,705
    Rep Power
    5

    Default Re: Synchronized Blocks in Static Methods Confusion

    Quote Originally Posted by MasterChief View Post
    One last curious question if you have 2 synchronized methods, but one synchronizes on this and the other synchronizes on the Class itself, are there 2 intrinsic locks which will allow an instance of the class to access both methods simultaneously?
    Watch your terminology there, this is a synchronized method:

    Java Code:
    public synchronized void thisMethodIsSyncedDude(){
    
    }
    What you are talking about is a method which applies synchronization.

    Java Code:
    public void thisMethodIsNotSyncedDude(){
      synchronize(lockObject){
         // ... but this part is
      }
    }
    Or perhaps you are talking about both? Its not really clear.

    Ask yourself this: are this and SomeClass.class the same object with the same door?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

Similar Threads

  1. Replies: 3
    Last Post: 06-30-2014, 11:55 PM
  2. Static Blocks
    By penguinCoder in forum New To Java
    Replies: 6
    Last Post: 10-13-2012, 03:22 AM
  3. How to handle synchronized blocks in clustered environments?
    By Arun_N in forum Threads and Synchronization
    Replies: 1
    Last Post: 04-16-2012, 04:36 PM
  4. alternative to static initialization blocks
    By paola in forum New To Java
    Replies: 1
    Last Post: 12-06-2008, 05:51 PM
  5. Replies: 0
    Last Post: 04-09-2008, 06:39 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •