java - Synchronization based on an object declared as "final static Object" vs. simply "final Object" -


this question has answer here:

i have question regarding java concurrency. if synchronize critical section based on object, difference between declaring variable final static object versus final object.

i understand static keyword defines variable belonging class, i'm little hazy on meaning in multi-threaded environment.

please refer code sample below. have lock object declared private final object lock = new object(), difference if add static keyword?

class concurrencysample {     private string message = null;     private final object lock = new object();     //private final static object lock = new object();      public void setmessage(string msg) {         synchronized (lock) {             message = msg;         }     }     public string getmessage() {         synchronized (lock) {             string temp = message;             message = null;             return temp;         }     }  } 

thanks help!

if declare object static final, there 1 lock shared across instances of class. means if 2 independent instances each try synchronize on it, 1 of 2 instances able lock @ time.

if declare object final, there 1 copy of lock per instance of class, if 2 independent instances of class each try acquire lock, they're each acquiring own locks, there's no blocking involved. however, if multiple threads invoke methods on 1 instance of class concurrently, threads try acquire same object, 1 thread can proceed @ time.

hope helps!


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -