1

Should a Predicate of springs Specification be static or nonstatic?

The default implementation would be similar as follows:

public static Specification<Customer> byCustomerName(String name) {
    return new Specification<Customer>() {
        @Override
        public Predicate toPredicate(Root<BasePricingCache> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            return cb.equal(root.get(Customer_.name), name);
        }
    };
}

But this could also be refactored to:

private static final CUSTOMER_SPEC = return new Specification<Customer>() {
    @Override
    public Predicate toPredicate(Root<BasePricingCache> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        return cb.equal(root.get(Customer_.name), name);
    }
};

public static Specification<Customer> byCustomerName(String name) {
    return CUSTOMER_SPEC;
}

What should be prefered? Are Specifications threadsafe and can be used this way?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

2 Answers2

1

You're refactored code wouldn't even compile. There's a superfluous return, CUSTOMER_SPEC doesn't have a type, and you're referring to a name variable that doesn't exist in the scope.

I think you're overthinking the issue here and are in the process of micro-optimizing. Keeping the Specification in a static factory method should be fine.

Oliver Drotbohm
  • 80,157
  • 18
  • 225
  • 211
0

Threadsafety wouldn't be a concern here for the implementation. You don't keep any state at all, every parameter is passed by the caller.

It could be micro-optimizing but your refactoring would be useful for example when a lot of instantiations happen of the specification. This could trigger the GC too often resulting in a noticeable lag in responsiveness.

The downside of these kind of micro-optimisations may be that you could end up with quite a memory requirement because the instance can't be GC'ed.

First back up your decision by gathering data (analysing the heap, ...) and test the impact of your solution on the application.

user392486
  • 195
  • 4