Lombok @singular-如何使其螺纹安全?
This is a question about Lombok's @Builder
and @Singular
annotations 和线程安全
为简化的例子,请考虑此类:
@Builder
public class Avengers {
@Singular
private List<String> members;
}
这会生成一个建造者,我可以在其中做到这一点:
final Avengers team = Avengers.builder()
.member("Iron Man")
.member("Thor")
.member("Captain America")
.build();
System.out.println(team.getMembers()); // ["Iron Man", "Thor", "Captain America"]
现在解决问题 - 我想做的就是这样(再次,这过于简单以提出要点):
final AvengersBuilder teamBuilder = Avengers.builder();
executorService.submit(() -> teamBuilder.member("Iron Man"));
executorService.submit(() -> teamBuilder.member("Thor"));
executorService.submit(() -> teamBuilder.member("Captain America"));
// shutdown and awaitTermination would go here
final Avengers team = teamBuilder.build();
为什么这是一个问题?
生成的构建器不是线程安全(Lombok通过arraylist
),所以<代码> team.getMembers()可能是不完整的,也可能是不一致的状态。
问题:有没有办法让Lombok产生一个线程安全构建器,使我可以使用这种“单数”模式?
到目前为止,我的解决方法是避免单数并创建我自己的ThreadSafe Builder方法,但是我我' M希望消除此样板。
This is a question about Lombok's @Builder
and @Singular
annotations and thread safety
As a simplified example, consider this class:
@Builder
public class Avengers {
@Singular
private List<String> members;
}
This generates a builder, where I can do this:
final Avengers team = Avengers.builder()
.member("Iron Man")
.member("Thor")
.member("Captain America")
.build();
System.out.println(team.getMembers()); // ["Iron Man", "Thor", "Captain America"]
Now for the problem - what I want to do is something like this (again, this is oversimplified to make the point):
final AvengersBuilder teamBuilder = Avengers.builder();
executorService.submit(() -> teamBuilder.member("Iron Man"));
executorService.submit(() -> teamBuilder.member("Thor"));
executorService.submit(() -> teamBuilder.member("Captain America"));
// shutdown and awaitTermination would go here
final Avengers team = teamBuilder.build();
Why is this a problem?
The generated builder is not threadsafe (Lombok backs it by an ArrayList
), so the result of team.getMembers()
may be incomplete or in an inconsistent state due to this.
Question: Is there a way to have Lombok generate a threadsafe builder that lets me use this "Singular" pattern?
My workaround thus far has been to avoid Singular and create my own threadsafe builder methods, but I'm hoping to eliminate this boilerplate.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不可能。无论如何,尝试通过多个线程共享一个建筑商是非常不寻常的。您会更好地存储所有结果,然后迭代它们,然后将它们全部添加到同一线程中的构建器中。
这仍然使项目的产生平行,这大概是慢的部分。
It's not possible. Anyway, trying to share a builder across multiple threads is highly unusual. You'd do much better to store all the results, then iterate them and add them all to the builder on the same thread.
This still parallelizes the generation of the items, which is presumably the slow part.