I am from .NET world, but now I am reading a book, where all examples are written in Java. Here is code snippet:
public class Order {
static class Builder {
private String security;
private int quantity;
public Builder() {}
public Builder buy(int quantity, String security) {
this.security = security;
this.quantity = quantity;
}
// some other builder pattern methods...
public Order build() {
return new Order(this);
}
}
private final String security;
private final int quantity;
private Order(Builder b) {
security = b.security;
quantity = b.quantity;
}
}
So if someone can explain me:
1. How can we have static class with non-static fields?
2. The author of the book is writing such thing:
By using the builders as the mutable object, you ensure the immutability of the Order
data members for easier concurrency.
Can someone give me an example, how it can actually simplify concurrency issues as soon as we still have mutable builder object, which would have the same concurrency issues, the same way we would have mutable Order
.
Q: How can we have static class with non-static fields?
The static
modifier means different things in C# and Java.
In C#, it means the class cannot be instantiated or subclassed. It basically makes the class a container for static
members.
In Java, the static
modifier on a class means it won't have an implicit reference to an instance of the outer class.
Docs:
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
Q: The author of the book is writing such thing: By using the builders as the mutable object, you ensure the immutability of the
Order
data members for easier concurrency.
The builder is mutable, but the actual object that is built is immutable (all of its fields are final
== readonly
in C#).
When an object is immutable, it is inherently thread-safe: you can use it in several threads at once without the need for locking, because it's guaranteed all these threads will only perform reads on the object. No need for synchronization means easier concurrency.