1

I want to create a class which will be accessed by multiple threads for getting a data. So I have a method like this:

public static String getData(){
 //some logic before returning the value
 // return data once initialized
}

Now there will be method which will set that data:

private void setData(){
}

I want this setData to be called only once, so thought of including it in static block:

static {
  setData()
}

Now I have these questions:

  1. I'm planning to create a static class for this, so that other threads can call like this:

    ThreadSafe.getData();

  2. In my getData, I want to check first the validity of that data before returning, if the data is invalid, I need to again call setData and then return it. Given this fact, I need to make getData synchronized right?

will my above approach work in a multi threading environment?

batman
  • 3,565
  • 5
  • 20
  • 41

3 Answers3

1

You can achieve it in multiple ways.

  1. You can use volatile variable ( If one Thread write/modify data and all other Threads read the data
  2. You can use AtomicReference variables ( If multiple threads can read/modify shared data)

If you have some atomic transaction on top of these variables instead of just write & read data, you have to protect your business transaction code block with synchronized or other alternatives like Lock API.

Refer to this jenkov tutorial for more details.

Related SE posts with code examples:

Difference between volatile and synchronized in Java

Avoid synchronized(this) in Java?

When to use AtomicReference in Java?

What is the difference between atomic / volatile / synchronized?

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
1

You can use synchronization:

public class ThreadSafe {

    private static final Object monitor = new Object();
    private static final String data;

    static {
        setData();
    }

    private static void setData() {         
            data = String.valueOf(System.currentTimeMillis());
    }

    public static String getData() {
        synchronized(monitor) {
            if (data.indexOf("7") < 0) { 
                // recalculate invalid data
                setData();
            }
            return data;
        }
    }
}
Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60
0

I would say you better synchronise (with double lock checking) block that calls setData() in getData(). Assuming it's a rare case this should work faster on high load.

Stan
  • 1,410
  • 10
  • 14