Use of volatile variable in Java

832 views Asked by At

I was reading a lot of forums and tutorials about volatile variables, but still not working for me. I'm working on app for Android in Android studio in Java.

I have main UI thread and from that I'm creating another using Runnable. I need to shere two variables between these two threads. UI thread changes these variables, another thread reads these variables.

Here is a fragment of my code. The code is not complete (not all lines about sensors - bcs it works well). I just don't know how to connect x,y in both threads that changes in UI will be visible in another thread.

thanks for any advice.

class MyThread implements Runnable {

    public static volatile float x = 0;
    public static volatile float y = 0;
    GLSurfaceView mGLView;

    public MyThread(float xPos, float yPos, GLSurfaceView GLView) {
        x=xPos;
        y=yPos;
        mGLView = GLView;
    }

    public void run() {
        while(true){
            ((MyGLSurfaceView)mGLView).mRenderer.ball.translateM(x, y, 0);
        }
    }
}


public class MainActivity extends Activity implements SensorEventListener {

    private GLSurfaceView mGLView;
    public static volatile float x = 0;
    public static volatile float y = 0;

    public void onCreate(Bundle savedInstanceState) {
        r = new MyThread(x, y, mGLView);
        new Thread(r).start();
    }

    public void onSensorChanged(SensorEvent event) {
        r.x = -(float)(event.values[2]/(1000*90.0));
        r.y = (float)(event.values[1]/(1000*180.0));
    }
}
1

There are 1 answers

1
OldCurmudgeon On

You should declare just one pair.

class Globals {

    public static volatile float x = 0;
    public static volatile float y = 0;

}

You can then change them anywhere:

    public void onSensorChanged(SensorEvent event) {
        Globals.x = -(float) (event.values[2] / (1000 * 90.0));
        Globals.y = (float) (event.values[1] / (1000 * 180.0));
    }

This is not necessarily good practice, I would probably declare a mutable Point class and hold it in a singleton but at least you need to share just one instance.