【发布时间】:2020-07-02 19:42:30
【问题描述】:
我想让我的 Builder 模式成为线程安全的但是面对这方面的问题,下面是我的代码:
// Server Side Code
final class Student {
// final instance fields
private final int id;
private final String name;
private final String address;
public Student(Builder builder)
{
this.id = builder.id;
this.name = builder.name;
this.address = builder.address;
}
// Static class Builder
public static class Builder {
/// instance fields
private int id;
private String name;
private String address;
public static Builder newInstance()
{
return new Builder();
}
private Builder() {}
// Setter methods
public Builder setId(int id)
{
this.id = id;
return this;
}
public Builder setName(String name)
{
this.name = name;
return this;
}
public Builder setAddress(String address)
{
this.address = address;
return this;
}
// build method to deal with outer class
// to return outer instance
public Student build()
{
return new Student(this);
}
}
@Override
public String toString()
{
return "id = " + this.id + ", name = " + this.name +
", address = " + this.address;
}
}
----------
还有一个名为 StudentReceiver.java 的类,我在其中使用了多线程:
class StudentReceiver {
// volatile student instance to ensure visibility
// of shared reference to immutable objects
private volatile Student student;
public StudentReceiver() throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() {
student = Student.Builder.newInstance().setId(1).setName("Ram").setAddress("Noida").build();
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
student = Student.Builder.newInstance().setId(2).setName("Shyam").setAddress("Delhi").build();
}
});
t1.start();
t2.start();
//t1.join();
//t2.join();
}
public Student getStudent() {
return student;
}
}
----------
下面是我调用这些方法的主类:
//Driver class
public class BuilderDemo {
public static void main(String args[]) throws InterruptedException
{
for(int i=0; i<10;i++)
{
StudentReceiver sr = new StudentReceiver();
System.out.println(sr.getStudent());
}
}
}
----------
我得到的输出如下:
null
null
null
null
null
null
null
null
id = 1, name = Ram, address = Noida
null
为什么我在这里得到空值? 谁能解释一下如何使 Builder Pattern 线程安全,以便它可以在多线程环境中使用。
【问题讨论】:
-
StudentReceiver代码对我来说毫无意义。你能解释一下你为什么要在那里做你正在做的事情吗? -
“为什么我在这里得到空值?” - 因为您在设置之前访问该字段。你的 Builder 没问题。构造函数在完成其工作之前不应返回。
标签: java design-patterns