Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the Builder pattern in the Effective Java book thread safe?

Tags:

java

I am reading 'effective java' - where it suggests using a builder pattern when classes have several optional construction arguments. The rational being it has advantages over -

'Telescoping pattern' - which basically provides one constructor with the require pattern, another with required + 1 optional, another with ' required + 2 optional' and so on - the author shares that this becomes too difficult to read and write when the optional parameters go out of control

'Javabeans' pattern - which uses a no argument constructor and then runs a setter for each parameter - the disadvantage here being thread safety - since the object goes through several methods - and may be accessible while under construction causing unexpected behavior in portions far removed from the code

The recommended pattern - builder - uses a 'static' inner class member in the class with optional arguments - clients build the 'builder' in the 'java beans' style construction and then invoke the class' constructor which basically uses the builders members for setting its fields

Phew!

My question : given that the builder is a static member, couldn't other threads in the application also access and potentially change the builders attributes concurrently? Causing unexpected behavior ?

No experience with thread programming so please pardon me if this is a stupid question

like image 927
Bi Act Avatar asked Mar 19 '23 11:03

Bi Act


1 Answers

There is a difference between a static member field (shares memory across all instances of said class), and a static inner class (does not see or share data with outer class).

Effective Java is promoting a pattern that uses the latter approach, which does not expose you to any thread safety issues.

If for whatever reason the same Builder instance were shared across two threads in your program, then yes, you have a thread safety issue.

like image 115
Amir Afghani Avatar answered Apr 07 '23 17:04

Amir Afghani