Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrency in bean validation

Reading the spec for JSR-303 :

The life cycle of a constraint validation implementation instance is undefined

The initialize method is called by the Bean validation provider prior to any use of the constraint implementation.

The isValid method is evaluated by the Bean Validation provider each time a given value is validated. It returns false if the value is not valid, true otherwise. isValid implementations must be thread-safe.

I cannot quite understand it. initialize is called prior to each isValid call, and isValid should be thread safe? Does it mean I cannot store anything in class level in initialize to access it later from isValid? Specially I need the annotation instance that is passed to initialize.

Can somebody shed light on it please?

like image 995
Arash Avatar asked Apr 11 '12 14:04

Arash


2 Answers

It doesn't say that initialize() should be called before each call of isValid(). It can be called only once before multiple calls of isValid() for the same annotation. For example, its javadoc says:

Initialize the validator in preparation for isValid calls.

like image 176
axtavt Avatar answered Sep 22 '22 12:09

axtavt


The initialize() method is called once for each constraint, while isValid() is called for every validation of a constraint.

It's perfectly ok to store the annotation (or single attributes of it) passed to isValid() into a field of the validator and access it later on from isValid(). You can find an example in the Hibernate Validator reference guide.

You just need to make sure that your isValid() method may be invocable by several threads in parallel (so for instance you may not alter the state of your validator from within isValid() without synchronization).

like image 40
Gunnar Avatar answered Sep 19 '22 12:09

Gunnar