[Java][?] ActionListener & Timer

Started by
6 comments, last by BitMaster 11 years, 1 month ago

ActionListener listener = new ActionListener()
        {
            @Override public void actionPerformed(ActionEvent e)
            {
                boolean isfin = false;
                do {
                    NSplitFrame += NSplitFrameInc;
                    if (NSplitFrame < 4 || NSplitFrame > 12)
                    {
                        NSplitFrame = 8;
                        NSplitFrameInc = -NSplitFrameInc;
                    }
                }while(isfin);
            }
        };
        displayTimer = new Timer(200, listener);
        displayTimer.start();

with or without the do :: while every once in a while I get a ArrayOutOfBoundsException due to NSplitFrame being > 12. Is there a way to make sure that this listener has completely finished while the values are being changed?

Sprite Creator 3 VX & XP

WARNING: I edit my posts constantly.

Advertisement

First and foremost, because you declare isfin as false and then go straight into your loop, the body of your loop will only run once every time, so you really have no need for your loop. Secondly, within your do-while, you need a statement that can change the value of your boolean isfin. Otherwise, if isfin is true, your program will loop endlessly, even if NSplitFrame is past your limits.

Now I don't know what you're using NSplitFrame for, but there are multiple ways of preventing your ArrayOutOfBoundsException. In most cases, if you're iterating through an array, it is recommended that you use a loop - usually a for loop. However, any loop can be written as any other loop (for, while, do-while).

If you can clarify what you're trying to do with your loop, I can be of a bit more help.

What is the size of your array? A 12 element array has valid indices 0..11. Also, it appears Timer tasks are run in a separate thread, and you don't appear to have any synchronisation on the values accessed and modified by this thread.


        if (NSplitFrame == 8)
                        NSplitFrame += NSplitFrameInc;
                    else
                    {
                        NSplitFrame = 8;
                        NSplitFrameInc = -NSplitFrameInc;
                    }

I changed it to this and so far it is good. How would I go about synchronization the actionListener and the main thread?

The value can only = 4, 8 or 12. But before the program might every once in a while = 0 or 16

Sprite Creator 3 VX & XP

WARNING: I edit my posts constantly.

Hum, first, you should decorrelate the frame index and the actual location of the frame in your array, thus having


0<=NSplitFrame <AnimationSize
 

. Then, the real frame is


RealSplitFrame = SplitFrameBase + NSplitFrame
 

Now I don't get your code, I mean it is an overcomplicated way to obtain either 8+NSplitFrameInc or 8-NSplitFrameInc.

Space Zig-Zag, a casual game of skill for Android by Sporniket-Studio.com

How would I go about synchronization the actionListener and the main thread?

One way is to ensure all access to the variables in question is in synchronized methods/blocks (provided you sychronize on the same object).

Here is a simple program that, at least on my system, illustrates the surprising effects that lacking synchronisation can have:

 
public class Example
{
    private int x;
    
    private int y;
    

    public /* * / synchronized / * */ int access() {
        return x - y;
    }
    
    public /* * / synchronized / * */ void modify() {
        ++x;
        ++y;
    }

    
    public static void main(String[] args) {
        final Example example = new Example();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    example.modify();
                }
            }
        });
        
        thread.start();
        
        try {
            for(int i = 0 ; i < 10 ; ++i) {
                int difference = example.access();
                System.out.println("Difference: " + difference);
                
                try {
                    Thread.sleep(1000);
                } catch(InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        } finally {
            System.exit(0);
        }
    }
}

One might naively expect that the two values will always be the same, so the difference should always be 0. A slightly less naive programmer might thing that the difference will always be 0 or 1, if the modifying thread is "between" incrementing X and Y.

Unfortunately, reality is much more complex. Without synchronisation, there are very few assumptions one can make about the output of this program. Without the synchronized blocks, here is sample output I got from running this program:

Difference: 0
Difference: -30
Difference: -12
Difference: -49
Difference: -60
Difference: -66
Difference: -37
Difference: -42
Difference: 0
Difference: -10

Quite surprising behaviour! This is known as a "race condition". Note the scary part: the result sometimes appears to be correct. It is possible to write code that looks like it works (under certain timing conditions), but may fail when those conditions change (like, when you release your application to the general public with faster or slower computers that you developed on).

However, removing the comments on both methods (thus ensuring that all access is correctly synchronized), gives us the "intended" output:

Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0
Difference: 0

There are other ways to synchronize programs.

That said, it appears the first result I found via Google where the general "Java Timer" class, not the "Swing Timer". The latter runs on the "event dispatch thread", so it is possible that, depending on where your other accesses occur, all accesses are performed on the same thread. You should carefully check that this is the case - if so, you do not need to synchronize your code.

Some really good info here. Little above me but I'll study rip-off's post for a bit.

ActionListener listener = new ActionListener()
        {
            @Override public synchronized void actionPerformed(ActionEvent e)
            {
                if (NSplitFrame == 8)
                    NSplitFrame += NSplitFrameInc;
                else
                {
                    NSplitFrame = 8;
                    NSplitFrameInc = -NSplitFrameInc;
                }
            }
        };
        displayTimer = new Timer(200, listener);
        displayTimer.start();

then made the function that uses NSplitFrame

@Override public synchronized void run() //Runable
{
        ...code here
}

Am I doing that right?

Sprite Creator 3 VX & XP

WARNING: I edit my posts constantly.

That won't do. Adding the synchronized keyword to a (non-static) method is basically just syntactic sugar for wrapping everything inside the method into a "synchronized(this) { }" block. However, the ActionListener is another instance and no synchronization at all will happen. You could probably use something like

@Override public void actionPerformed(ActionEvent e)
{
   synchronized(OutsideClassName.this)
   {
      // what you did before
   }
}
where OutSideClassName has to be replaced by the class in which you define the action listener and with which you need synchronization. A probably better alternative would be to not do anything specific in the action listener and instead call a (synchronized) method of that class to do the work.

This topic is closed to new replies.

Advertisement