Current Position:Home > Problem with Threads and a static variable

Problem with Threads and a static variable

Update:10-11Source: network consolidation
Advertisement
I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
Code functionality:
A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
The problem as far I understand is:
Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
Thanks,
B.D.
Code:
private static volatile boolean bChanged = false;
private static Thread objMainProcess;
   protected static void Init(){
        objMainProcess = new Thread() {
            public void run() {
                while( objMainProcess == Thread.currentThread() ) {
                   GetState();
        objMainProcess.setDaemon( true );
        objMainProcess.start();
    public static void initStatusTimer(){
        if(objTimer == null)
             objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                public void actionPerformed( java.awt.event.ActionEvent evt){
                          SetState();
    private static void SetState(){
        if( objMainProcess == null ) return;
        synchronized( objMainProcess ) {
            bChanged = true;
            try{
                objMainProcess.notify();
            }catch( IllegalMonitorStateException e ) {}
    private static boolean GetState() {
        if( objMainProcess == null ) return false;
        synchronized( objMainProcess ) {
            if( bChanged) {
                SendMessage();
                bChanged = false;
                return true;
            try {
                objMainProcess.wait();
            }catch( InterruptedException e ) {}
            return false;
    }

The Best Answer

Advertisement
Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
Again as you said, There is a reason I can't call sendMessage() inside setState().
The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
Thanks,
B.D.
  • Problem with Threads and a static variable Update:10-11

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please. Code functionality: A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. T

  • Problem to override a public static variable Update:11-30

    Hello, I have a problem when trying to override a public static value. Here is my example. I have one class defining var szName public class myClass1 { public static String szName = "First Name"; And an extention public class myClass2 extends my

  • Can volatile variable be called as static variable for threads? Update:11-30

    I am trying to understand volatile variable, and it's uses. I was thinking of using it to make it shared variable between threads, but not between object instances. public class VolatileExample extends Thread {   volatile int x = 1;   public void f()

  • Slow performance when multiple threads access static variable Update:11-30

    Originally, I was trying to keep track of the number of function calls for a specific function that was called across many threads. I initially implemented this by incrementing a static variable, and noticed some pretty horrible performance. Does any

  • Static variables and JAR files problem Update:11-30

    Hello All, I am trying to get two applets to communicate. Both are held in the same JAR file loaded from the same location. The JAR file also contains a class with some static variables which are used to comunicate between the two applets. The applet

  • SingleThreadModel-static variables thread safe? Update:11-30

    Hi.. I have one servlet which implements SingleThreadModel.My servlet contains two static variables . public class MyServlet extends HttpServlet implements SingleThreadModel { private static String firstName="Umar hathab"; private static StringB

  • To use a static variable in another class,but report NullPointerException Update:10-11

    when TableMain is running,I run testRecord so that let TableMain add a occur informatin and happened time in a row in TableMain,but when I run testRecord,java report a NullPointerException and I dont know how to solve this problem,thanks for helping

  • Non-static variable in multithreaded servlet Update:10-11

    I have a multithreaded servlet and a counter variable to keep count of when each thread finishes executing. I have set the variable to be a static integer. The problem is that the counter variable persists across requests whereas I want it to reset w

  • Static variable, a bug in applet classloader, Java plug-in? Update:11-30

    I found a potential bug in java plug-in. Environment, 1. IE 6.0 2. Windows XP 3. JRE 1.3.1.06 and JRE 1.4.1.01 Steps, 1. build a very simple applet (attached below) 2. embed the applet into a .html page. 3. enable java plug-in for IE and Netscape. 4.

  • How to reference a static variable before the static initializer runs Update:11-30

    I'm anything but new to Java. Nevertheless, one discovers something new ever' once n a while. (At least I think so; correct me if I'm wrong in this.) I've long thought it impossible to reference a static variable on a class without the class' static