Do you think it is really immutable? [...] Is this really thread safe?
No part of your code is immutable. This also probably hampers thread safety; that said it's really difficult to declare that a class is or isn't thread-safe in a binary fashion. I also don't see why you would ever share builder instances between threads in the first place, but I might be mislead by the simplicity of your code sample.
To make achieving thread-safety easier, your Builder
s should be themselves immutable. This means that every withXXX()
method should return a new builder that represents the new state. (There's probably more clever ways of doing this but that would be the straightforward approach.)
Just to reiterate though: I'm not sure it's strictly necessary to make a builder thread-safe - most of the time they're objects with a very short lifetime and scope of visibility. Whether you want to make them immutable depends on the use case, you might want to store partially filled builders but that's also somewhat rare. (Subjectively it does however seem more intuitive for a method whose name starts with with
to not modify an object in-place, as opposed to one whose name starts with set
.)
Do you think that this builder would have any limitation in what regards the scenario where it can be used?
This is generally unanswerable, but if you do make your Person
objects immutable, and thus only constructible by your builder, they'll be unusable as JPA entities, my guess is as JSF backing beans as well. Java frameworks that create/manage certain objects for you more often than not expect them to be JavaBeans, meaning that these objects can be created by calling a no-args constructor and property setters through reflection.