rock wells
rock wells

Reputation: 61

Spring Injection - Thread safe

public class Test{
private First first;
private Second second;

public void setFirst(First first){
this.first = first;
}
public First getFirst(){
 return first;
}
// same approach for second
}

If I inject the instance through spring injection, is it thread-safe? If not, how to make it thread-safe? I googled and found contradict responses, not able to come to any conclusion.Please suggest. Thanks in Advance. -RW

Upvotes: 4

Views: 6294

Answers (3)

Mr.Eddart
Mr.Eddart

Reputation: 10273

The injection of the dependencies is handled by Spring, you should not care about the thread safety of the getters and setters, because Spring is going to inject the dependencies taking in account that you have no synchronization logic.

Also, no other thread (i.e. the threads of your application) is going to use the beans until the context is completely configured and all the dependencies have been injected.

You should not worry about thread safety of the dependency injection, Spring does (most likely, spring is going to use just one thread to inject all the dependencies).

Upvotes: 0

skaffman
skaffman

Reputation: 403581

If you're talking about what I think you're talking about, then it's an interesting discussion.

Technically, because setFirst() and getFirst() are not synchronized, then it's possible for setFirst() to inject one object on Thread 1, and getFirst() to return a different object on Thread 2. The Java memory model reserves the right to make this "eventually consistent", as they say.

So in the case of Spring, which configures its bean graph during startup (or the server's internal startup thread), it's possible that the HTTP request threads (for example) would not see that bean graph properly, due to the lack of synchronization.

Note: this has nothing to do with concurrent access. Even if the HTTP requests come in after Spring has initialized, the Java memory model does not guarantee that those threads will see the correct data.

In practice, this never happens (at least, I've never seen it happen). The lack of synchronization is only really a problem for concurrent threads, which isn't the issue here.

So it's really just an academic argument.

If this isn't what you're talking about, my apologies. It's still an interesting thought, though.

Upvotes: 7

Dewfy
Dewfy

Reputation: 23644

Assuming that you have created singleton instance of Test and trying to set/get value (a) from Spring (b) from another part of you program. In this case just make your get/set pair synchronized:

public synchronized void setFirst(First first){
    this.first = first;
}
public synchronized First getFirst(){
    return first;
}

I don't see other unsafety from multithreading

Upvotes: -1

Related Questions