-1

I could not find any definitive answer to my question elsewhere so I'm deciding to ask.

I am having porting code into Java and making it threadsafe. I'm applying as many getters/setters as I can on objects and passing them around. And obviously these values are not set as static. But I'm also looking at other angles.

For any particular thread I want all methods in a class to be able to access a class variable without other threads interfering (and WITHOUT synchronized variable keyword), is the following acceptable?

public class TestClass {


    public double testVal;


    public void methodA() {
        testVal = 22.6;
    }



    public double methodB() {
        return testVal;
    }
}

If I create an instance of TestClass in main and call methodA then methodB on that object, it returns my testVal. This problem is to be scaled up with many many values shared across different methods in the class as i'm just showing a simple demo.

Is this a good threadsafe approach? This data would be stored on the thread stack rather than the heap if I'm correct?

Cheers

arsenal88
  • 1,040
  • 2
  • 15
  • 32
  • I don't think that is ThreadSafe. Your Test Class object can be updated by multiple threads. Are you trying to make the `testVal` variable thread safe? – Sam Orozco Jul 30 '18 at 16:25
  • Yes I am trying to – arsenal88 Jul 30 '18 at 16:26
  • 1
    Why don't you want to use the `synchronized` keyword? – Sam Orozco Jul 30 '18 at 16:27
  • Because I'm porting for a wider application that cannot allow the (small) timelag involved with synchronized keyword – arsenal88 Jul 30 '18 at 16:28
  • I don't think you're going to get around the small delay with synchronizing, but have you looked into **Mutexes**? https://stackoverflow.com/questions/5291041/is-there-a-mutex-in-java – Sam Orozco Jul 30 '18 at 16:31
  • The description is not clear - is each thread going to have it's own `TestClass` instance (which is thread safe since `testVal` is not static) or will there be a single `TestClass` instance shared by multiple threads (definitely not thread safe). – Andrew S Jul 30 '18 at 16:35
  • Each thread to have it's own TestClass instance – arsenal88 Jul 30 '18 at 16:37
  • 1
    There is no thread-safety issue since the currently executing thread knows only about its own instance. – Andrew S Jul 30 '18 at 16:39

1 Answers1

0
There are many ways to make your class thread safe.

1. You can make your variable as volatile as in the example you have asked , if the current state of testval does not depend upon the previous state
2. You make the variable as private and volatile and use synchronization for all the methods that are modifying the state of your object.
3. Make the class as immutable
4. Make the calss as stateless
5. Guard all the method with synchronized keyword that are modifying the state of the variables. 
Dinesh
  • 1,046
  • 1
  • 8
  • 17