• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

Do I have to create new instance for each instance of Validator?

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When validating objects using Validator interface (with supports() and validate() methods) I first make a class that implements Validator and then logically implement those two methods. After that I invoke it inside some controller. Question is related concurrency and thread safety and it is: do I make new instance of Validator each time I am validating something, or I can make Validator instance singleton and simple inject it in my controller? Can something go wrong if I use same instance of Validator for each REST request in controller?
 
Sheriff
Posts: 22716
129
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Stefan Jankovic wrote:Can something go wrong if I use same instance of Validator for each REST request in controller?


If the Validator instance is thread-safe or, even better, immutable, then feel free to create a singleton and inject it. If it isn't, make it request scoped and still inject it. Let Spring worry about instantiating it.
 
Saloon Keeper
Posts: 26536
187
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I cannot speak with full authority on Spring validators specifically, but as a general rule, validators are stateless. Their primary purpose is to accept an input and return judgement with no long-term context. So no. Besides, if the validator is a Spring Bean, Spring Beans are by default singletons anyway.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic