0

I would like to understand if using a non-final variable would cause a race condition. I have a spring boot application where we instantiate a finagle client like shown below. Can this cause a race condition. If so why?

public class Client{

private JavaService<Request,Response> client;

Client(Config config){ 
this.client = create(config);
}

public CompletableFuture<Request, Response> testClient() {
 return client.apply();
}

}
user3310115
  • 1,372
  • 2
  • 18
  • 48
  • As long as you do not reassign it, it does not matter – Antoniossss Mar 07 '22 at 06:56
  • @Antoniossss It can if it's accessed by other threads. – shmosel Mar 07 '22 at 07:02
  • @shmosel Its preset on construction time. – Antoniossss Mar 07 '22 at 07:04
  • That's fine. But why is it non-final? That implies you might be doing something which isn't fine. – tgdavies Mar 07 '22 at 07:07
  • @Antoniossss Doesn't matter. If it's not [safely published](https://shipilev.net/blog/2014/safe-public-construction/#_safe_publication), it can be seen in a partially-constructed state by another thread, because there's no automatic *happens-before* edge between construction and assignment. – shmosel Mar 07 '22 at 07:09
  • But its different as it reffers to lazy creation of object (in multi thead execution). Here you dont have that scenario and it would have to be dealt with on the caller level, in which case final not volatile nor any other modifier will help on this level – Antoniossss Mar 07 '22 at 07:19
  • My assumption here is that OP is creating shared `Client` and passes it along to a worker threads and not creating it on the fly upon first usage by any worker. I am aware of double check locking and its consequences and in my opinion it does not apply here. @shmosel – Antoniossss Mar 07 '22 at 07:24
  • I didn't say anything about DCL (it's only used as an example in my linked article). My point is, when you construct an object without final fields, it can be seen in an unconstructed state by another thread, depending on how it's shared. Given that OP didn't clarify if or how it's being shared, that should remain a concern. – shmosel Mar 07 '22 at 07:32
  • 1
    I see your point and you are right https://stackoverflow.com/a/7145024/1527544 – Antoniossss Mar 07 '22 at 07:40

0 Answers0