views:

60

answers:

2

I have a class that serves as a delegate to another.

public class Delegate {

    private AnotherClass ac;

    public void delegateCall() {
        this.ac.actualCall();
    }

    public void setAC(AnotherClass ac) {
        this.ac = ac;
    }
}

What are the ramifications if I have lots of threads calling delegateCall() and another thread calls setAC()? My assumption is that some of the threads calling delegateCall() would get access to the ac instance before it was set and some would get access to it after it was set. In my particular application, it does not matter which instance each thread gets.

My question: Is there any underlying synchronization that may happen within the JVM that might cause the threads calling delegateCall() to block?

+3  A: 

No, there's nothing that will block here. There's also nothing to guarantee that a "reader" thread will ever see the change to ac. In reality it almost certainly will, but it's not guaranteed (as there are no "happens-before" barriers involved in the code you've shown here. That may well be okay for your situation of course.

Jon Skeet
A: 

After reading the description of your task I think it'll be interesting for you to assume using Objects Pool.

In your code, as Jon said, nothing prevents you from getting NullPointerException.

Roman