1

I stumbled upon an question which is not clear for me.

A. Using Java 1.4, wrap the following function in a thread so that it can be called asynchronously and provide a way for the return value to be retrieved at a later time:

B. How would the same be done in Java 5

int someMethod(int i) { return i++; }

What I think is one of the solutions: Write a class with two public methods void synchronized calculate(int i) and int getValue() . The calculate starts the thread and and set a private variable.

In java 1.5 I can use AtomincInteger. Is that an answer?

Roman C
  • 49,761
  • 33
  • 66
  • 176
Lukasz Madon
  • 14,664
  • 14
  • 64
  • 108

3 Answers3

1

In Java 1.5, I'm pretty sure you would use a Future to return the result. I'm not sure about the 1.4 equivalent, but it looks like this question covers the same ground.

Community
  • 1
  • 1
Don Kirkby
  • 53,582
  • 27
  • 205
  • 286
0

Mybe you can use double check locking in 1.5 or later:

private volatile int privateValue = 0;

public void calculate(int i) {
    int result = getValue(i);
    if (privateValue != result) {
        synchronized (this) {
            if (privateValue != result) {
                privateValue = result;
            }
        }
    }

}

public int getValue(){
    return privateValue;
}

Be sure you privateValue must declare as volatile.

More info about double check locking.

The "Double-Checked Locking is Broken" Declaration.

Community
  • 1
  • 1
lichengwu
  • 4,277
  • 6
  • 29
  • 42
0

Let the calculate() method put the result in a BlockingQueue queue, and getValue() method invoke queue.take(), thus waiting in case the result is not calculated yet.

Note additional programming efforts required if the getValue() method can be invoked several times.

Alexei Kaigorodov
  • 13,189
  • 1
  • 21
  • 38