aruuuuu aruuuuu - 1 month ago 13
Java Question

javax.validation.Validation multiple instantiation Vs Reusing single Validator instance

I am using javax.validation.Validation to validate jpa entities. I am always validating against the same Entities.

I would like to know if it is better to use one Validator for all validations or to instantiate a new Validator each time I validate.

As well, how expensive in terms of computation is it for me to instantiate a new validator each time I would like to use it?

Option1: instantiate new validator for each validation.

public class Validator
{

public static void main(String[] args)
{


//Validation1
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();

Entity entityToValidate = new Entity();
entityToValidate.setEmail("NOT_A_VALID_EMAIL@@@tomanyat.com");
Set<ConstraintViolation<T>> constraintViolations = validator.validate(entityToValidate);





//Validation2 (Note that validator has been created yet a second time !! )
Validator validator2 = factory.getValidator();

Entity entityToValidate2 = new Entity();
entityToValidate.setEmail("NOT_A_VALID_EMAIL@@@tomanyat.com");

Set<ConstraintViolation<T>> constraintViolations2 = validator2.validate(entityToValidate);



}


}


Option2: single validator for all validations.

public class Validator
{

public static void main(String[] args)
{
//Validator created only once
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();


//Validation #1
Entity entityToValidate = new Entity();
entityToValidate.setEmail("NOT_A_VALID_EMAIL@@@tomanyat.com");

Set<ConstraintViolation<T>> constraintViolations = validator.validate(entityToValidate);




//Validation #2
Entity entityToValidate2 = new Entity();
entityToValidate.setEmail("NOT_A_VALID_EMAIL@@@tomanyat.com");


Set<ConstraintViolation<T>> constraintViolations2 = validator .validate(entityToValidate);



}


}

Answer

Note how the Validator javadoc states

Validates bean instances. Implementations of this interface must be thread-safe.

As such a Validator should't really contain state, unless that state is also thread-safe. Therefore, you shouldn't need to create a new Validator instance, just re-use the same one, depending on the types obviously.

As well, how expensive in terms of computation is it for me to instantiate a new validator each time I would like to use it?

This depends on your Validator. But the instantiation (creating but not initializing the object) itself is almost completely negligible, especially when you consider all the processing that a JPA implementation performs.

Comments