Static nested class thread safety - java

builder, java, multithreading

Solution

If I try to create two instances of MyClass using the builder simultaneously from two threads, will it be safe?

If you mean using the same instance of `Builder` in both threads then no, but if each thread has its own instance of the `Builder` then you'll be fine. With this kind of pattern:

MyClass c = new MyClass.Builder().height(10).weight(2).build();

each `Builder` instance is local to a single thread.

Problem

I have a static "Builder" class inside a class called "MyClass". If I try to create two instances of MyClass using the builder simultaneously from two threads, will it be safe ? Can values set by one thread be assigned to object created by another thread ? Code: ``` public class MyClass { private int height; private int weight; private MyClass(Builder builder) { height = builder.height; weight = builder.weight; } public static class Builder { private int height; private int weight; public Builder height(int h) { height = h; return this; } public Builder weight(int w) { weight = w; return this; } public MyClass build() { return new MyClass(this); } } } ```

Original source