Search code examples
javaclassvolatileextends

extending class and making variables volatile


I have this vector class:

public class Vector {
    public double x;
    public double y;

    public double getLength() {
        return Math.sqrt(x*x+y*y);
    }
}

Most of the time i just want to use it like it is, but for a certain case i want to use a volatile version of it, so i tried extending it:

public class VectorVolatile extends Vector {
    public volatile double x;
    public volatile double y;
}

The idea behind it is to use all the functions that are in the original class also for the volatile class. But this doesn't work. The variables (x, y) will not get replaced correctly.

I want to use volatile because I have 2 threads. One thread reads and writes to the object, the other one only reads. I would like to use volatile instead of synchronized because i think its faster and since the one thread only reads, setting the variables to volatile should be enough.

Is there a way to get all the functions from the original class without copy and paste? Should i not use volatile?


Solution

  • By extending you did not change the properties of the member of the Vector class.

    When you extend the class and declare a new member under the same name, then it will shadow the old member. That is, in the class VectorVolatile this.x and super.x are just two different members. One is volatile, the other is not.

    https://dzone.com/articles/variable-shadowing-and-hiding-in-java

    (IMHO, it is not a good idea to make a non-thread-safe class thread safe by extending it).

    A cleaner way may be to define an interface for a class providing x and y, have you methods operate on that interface and then have different implementation for the class providing x and y.