Results 1 to 5 of 5
  1. #1
    sandeepsai39 is offline Member
    Join Date
    Feb 2009
    Posts
    96
    Rep Power
    0

    Default can we synchronise static variables

    I am new to java .

    My doubt is can we synchronise static variables,that means static variable can be used in multithreading concept.

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    You need to write static getter and setter methods and synchronize those
    Java Code:
        private static int var;
        
        public static synchronized void setVar(int i) {
            var = i;
        }
        
        public static synchronized int getVar() {
            return var;
        }
    and use only those methods to access the variable, of course.

    The exact same way you "synchronize" anything else, of course.

  3. #3
    sandeepsai39 is offline Member
    Join Date
    Feb 2009
    Posts
    96
    Rep Power
    0

    Default

    that means if we want to use a static variable in multithreading concept we can not assign static variable like ClassName.staticvar = something from any where.

  4. #4
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Well what did I say?

    Not doing that may still get the same value to all threads eventually but there is no guarantee as to when, or if as all threads will have "local" copies of the reference values.

    You must, of course, then do
    Java Code:
    ClassName.setVar(value);
    // and
    value = ClassName.getVar();
    rather than
    Java Code:
    ClassName.var = value;
    // and
    value = ClassName.var;
    What is it about this that puts you off? It's not as though its all that much more to type, is it?
    Last edited by masijade; 09-02-2010 at 01:15 PM.

  5. #5
    sandeepsai39 is offline Member
    Join Date
    Feb 2009
    Posts
    96
    Rep Power
    0

Similar Threads

  1. Replies: 6
    Last Post: 02-15-2010, 04:31 AM
  2. What are Instance variables and static variables?
    By sandeshforu in forum New To Java
    Replies: 3
    Last Post: 09-09-2009, 05:48 PM
  3. static are instance variables
    By gabri in forum Advanced Java
    Replies: 12
    Last Post: 09-30-2008, 06:30 PM
  4. Using Static Variables
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-16-2008, 11:08 PM
  5. Help with static variables
    By bbq in forum Advanced Java
    Replies: 1
    Last Post: 06-28-2007, 05:38 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
  •