Concurrency in bean validation
Asked Answered
Y

3

7

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?

Yumuk answered 11/4, 2012 at 14:42 Comment(0)
B
4

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.

Burwell answered 11/4, 2012 at 14:56 Comment(2)
it saye 'prior to ANY use' doen't it implies that?Yumuk
@Arash: As far as I understand "prior to any use" doesn't mean "before every use", it means that no use of uninitialized instance is allowed.Burwell
H
3

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).

Harpist answered 12/4, 2012 at 20:43 Comment(0)
R
1

Also wanted to mention that the validator is initialized with initialize() per each class.

So if you have DummyClassA and DummyClassB using the SAME validator, initialize will be called twice for each. DummyClassB will initialize its own validator and will not use DummyClassA initialized validator and vice versa. Any new instance of DummyClassA or DummyClassB will use the same validator for each. So if you have four instances of DummyClassA, they will all use the same validator initialized for DummyClassA.

So...DummyClassA has a many to one relationship with a validator and DummyClassB will also have a many to one relationship with a valdiator.

This was something my team and I were curious about when reading the line you read and having concerns of it not being thread safe and such!

Roti answered 17/8, 2018 at 16:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.