Search code examples
javaglobal-variablesthread-synchronization

Global Variable in Java for Synchronization


I am writing a variation of the Multiple Sleeping Barber problem in JAVA, where each customer has a time of tolerance for waiting for the barber and a specific time for having their hair cut, plus in addition to sleeping when there are no customers, each barber sleeps after cutting the hair of a certain number of customers for a specific time.

Due to the variation I feel the need for a global variable which keeps track of the time.

My question is, will I face any problems if I use a Global class with static fields for tracking time? I have read that if my global class becomes "unloaded" the value would become null; when does this happen and will it be an issue in my case? If it is, what other options do I have?

(I would increament time in a "while" loop in my main class which extends Thread and the Customer and Barber classes which also extend thread will only need to read it).


Solution

  • Here is a similar question: when static class initialization. And based on JLS 12.4.1, A class static variable will be initialized after one of these following events happen:

    • an instance of the class is created
    • a static method of the class is invoked
    • a static field of the class is assigned,
    • a non-constant static field is used, or
    • for a top-level class, an assert statement lexically nested within the class is executed.

    So in your case, I guess you need assure your global time variable is assigned before enter that while loop by a simple assignment, like

    public class Global {
      public static int time;
    }
    
    public class MultipleSleepingBarber implements Runnable {
    
      public void run() {
        Global.time = Global.time + 1;
        System.out.println("Time is " + Global.time);
      }
    
      public static void main(String args[]) {
        Global.time = 0;
        for (int i = 0; i < 10; i++)
          (new Thread(new MultipleSleepingBarber())).start();
      }
    
    }