Home > Back-end >  Can a same lombok builder be access/update by multiple threads?
Can a same lombok builder be access/update by multiple threads?

Time:09-02

@Builder
public class X {
    @Nonnull String a;
    @Nonnull String b;
}
main () {
  X.XBuilder builder = X.builder();

  //thread 1
    CompletableFuture.runAsync(()-> {
        builder.a("some");
     });

  //thread 2
    CompletableFuture.runAsync(()-> {
        builder.b("thing");
     });
}

Here the same object is being accessed and modified at the same time. So will this code be thread safe?

Usecase is like wants to call multiple api's, each api results is to populate the fields of class X.

CodePudding user response:

If you want to know how the stuff that Lombok generates works, you can always use the delombok tool.

With regard to thread safety of @Builder, you will see that you can in fact access a builder instance from multiple threads, but only under these constraints:

  • Don't call the same field setter from different threads. Otherwise you'll never know which value makes it to the builder eventually.
  • Make sure that all value-setting threads have terminated before you call build(). (If you want to call build() in a thread, too, make sure you create this thread after all value-setting threads have terminated.)

This is necessary because @Builder wasn't designed for concurrency (as that's not something you typically do with a builder). In particular, @Builder does not use synchronization or volatile fields, so you have to create a happens-before relation for all setter calls with the build() call.

  • Related