batman batman - 5 months ago 12
Java Question

How to design the class, which will be accessed by multiple threads.

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?

Answer

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;
        }
    }
}
Comments