S
S
Sergei Chamkin2021-02-27 19:41:26
Java
Sergei Chamkin, 2021-02-27 19:41:26

Why is using synchronized in setter bad?

This question came up in an interview.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2021-02-27
@sergey-gornostaev

Perhaps because the setter must be used to set the value of a single field, and using synchronized for this is redundant.

B
BorLaze, 2021-02-27
@BorLaze

Because it usually doesn't make any sense.
Unless you take into account something like

void setVar(int var) {
  if(var == null) {
    this.var = var;
  }

but it is no longer a setter.
And in the case of a simple assignment, there is no difference between two consecutive value settings in two consecutive calls or in two parallel ones.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question