leadpony / justify

Justify is a JSON validator based on JSON Schema Specification and Jakarta JSON Processing API (JSON-P).
Apache License 2.0
96 stars 18 forks source link

value of class attribute persists between subsequent calls to the custom validation #36

Closed ghost closed 5 years ago

ghost commented 5 years ago

I am implementing a custom validation by implementing the interface FormatAttribute.

public class MyCustomerValidation implements FormatAttribute {
  private boolean attribute1 = true;

  @Override
  public boolean test(JsonValue value) {
    System.out.println("Value of attribute1 before test " + attribute1);
    attribute1 = customTestLogic();
    System.out.println("Value of attribute1 after test " + attribute1);
    return attribute1;
 }

  private customTestLogic() {
    return false;
  } 
}

In the above example, I have attribute1 initialized to true value. In the method test say a customTestLogic sets this attribute1 value to false. Now, on second invocation, the false value of attribute1 persists. I guess every new request should create a new object of this class. For example with current implementation this is the output: First invocation:

Value of attribute1 before test true
Value of attribute1 after test false

Second invocation:

Value of attribute1 before test false
Value of attribute1 after test false

The correct expected behavior should be: First invocation:

Value of attribute1 before test true
Value of attribute1 after test false

Second invocation:

Value of attribute1 before test true
Value of attribute1 after test false
leadpony commented 5 years ago

Hi @adityamandhare Each implementation of FormatAttribute, ContentMimeType, and ContentEncodingScheme interface defined in the spi package, are instantiated once at startup and the single instance will be shared between ALL schemas and validations. This is intentionally designed. I have updated the Javadoc to clarify this design. Object creation through ServiceLoader mechanism is considerably slow. If many instances should be created, we must introduce new factory interfaces to implement such as FormatAttributeFactory in addition to the current interfaces.

ghost commented 5 years ago

okay I got that. Thanks @leadpony 🙂