Fixed Delay Scheduling with Quartz

 

With this (Fixed Delay) kind of scheduling there is always a same fixed delay between termination of one execution and commencement of another, as can be shown in the following image.

fixed-delay-scheduling

Java supports this kind of scheduling inherently through java.util.Timer and java.util.concurrent.ScheduledExecutorService, however achieving fix delay using quartz is not that straight forward (Specially when misfires are considered)

One might consider the easy approach, of rescheduling itself from within the execute method of quartz job.

quartz-schedule

Here is the implementation, you would keep the reschedule method in util class as static method.

quartz-reschedule-from-job

However, a better approach would be to use Quartz listeners:

quartz-reschedule-from-listner

Here is the implementation of the listener

quartz-reschedule-from-listner-code

Here is the usage :

quartz-reschedule-from-listner-usage

Here is the code for FixdedDelayJobData.java and FixedDelayJobListener.java

Scalable Java Thread Pool Executor

Ideally from any Thread Pool Executor, the expectation would be the following

  • An initial set of threads (core threads pool size) created up front, to handle the load.
  • If the load increases, then more threads should be created to handle the load up to max threads (Max pool size)
  • If the number of threads increases beyond Max Pool Size, then Queue up the tasks.
  • If Bounded Queue is used, and the queue is full then bring in some rejection policy.

The following diagram depicts; only initial threads are created to handle tasks (When load is very low).

tpe-core-threads

As more task come in, more threads are created to handle the load (Task queue is still empty), if total number threads created is less than max pool size.

tpe-extended-threads

Task Queue getting filled up if total number of tasks is more than total number of threads (initial + extended)

tpe-queue-filling-up

Unfortunately, Java Thread Pool Executor (TPE) is biased towards queuing rather than spawning new threads, i.e., after the initial core threads gets occupied, tasks gets added to queue, and after the queue reaches its limit (Which would happen only for bounded queue), extra threads would be spawned. If the queue is unbounded then extended threads won’t get spawned at all, as depicted in the following image.

tpe-java-implementation

1==> Initial Core threads were created to handle the load

2==> Once there are more tasks than number of core threads, queue starts getting filling up, to store the tasks

3==> Once the queue is filled, extended threads are created.

Here is the code in TPE, which has problem

tpe-problem

We have got couple of work around:

Work Around #1

Set the corePoolSize and maximumPoolSize to same value and set allowCoreThreadTimeOut to true.

Pros

  • No coding hack required

Cons

  • There is no real caching of threads as threads are getting created and terminated quite often.
  • There is no proper scalability.

Work Around #2

  • Override the offer method of delegator TransferQueue, and try to provide the task to one of the free worker threads, return false if there is no waiting threads,
  • Implement custom RejectedExecutionHandler to always add to Queue.

tpe-rejection-handler

Refer this implementation for more detail

Pros

  • TransferQueue ensures that threads are not unnecessarily created, and transfers the work directly to waiting thread.

Cons

  • Customized rejection handler cannot be used, since it is used to insert the the tasks to queue.

Work Around #3

Use custom queue (TransferQueue) and override the offer method to do the following

  1. try to transfer the task directly to waiting thread (if any)
  2. If above fails, and max pool size is not reached then create extended thread by returning false from offer method
  3. otherwise insert into queue

tpe-refer-executor-in-queue

Refer this implementation for more detail.

Pros

  • TransferQueue ensures that threads are not unnecessarily created, and transfers the work directly to waiting thread on the queue.
  • Custom Rejection Handler can be used.

Cons

  • There is a cyclic dependency between Queue and Executor.

Work Around #4

Use Custom Thread pool executor, specially dedicated for this purpose, It uses LIFO scheduling as described in Systems @ Facebook scale

Jackson Mixin To The Rescue

Many a times it is not possible to annotate classes with Jackson Annotations simply for serialization/deserialization needs. There could be many reasons, for example

  • Classes which needs to be serialized/deserialized are 3rd party classes.
  • You don’t want Jackson invade into your code base every where.
  • You want cleaner and modular design.

Jackson Mixin feature would help solve above problems easily. Lets consider an example :

Let’s say you want to serialize/deserialize following class (Note that it does not have getter/setter)

 public class Address {

	private String city;
	private String state;

	public Address(String city, String state) {
		this.city = city;
		this.state = state;;
	}

	@Override
	public String toString() {
		return "Address [city=" + city + ", state=" + state +  "]";
	}
}

If you try to serialize, you would get the following error

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class com.some.package.Address and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

To solve the above issue, you have to do the following

  1. Add a default constructor
  2. Add getter/setter for each property

However that is not possible for many cases. Here we can use Jackson Mixin to get around with this problem, to do that we have to create corresponding mixing class, as can be seen here, constructor should match as that of your source object and you have to use Jackson annotations (@JsonCreator, @JsonProperty etc.)

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public abstract class AddressMixin {

    @JsonCreator
    public AddressMixin(
            @JsonProperty("city") String city,
            @JsonProperty("state") String state) {
        System.out.println("Wont be called");
        
    }
}

Still you will get the following exception

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class com.some.package.Address and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) )

It turns out that, we have to tell jackson to use reflection and access the fields.

mapper.setVisibility(mapper.getSerializationConfig()
        	.getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

Here is the teset code:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonMixInTest {

	public static void main(String[] args) throws IOException {
   
	Address address = new Address("Hyderabad",  "Telangana");

        ObjectMapper mapper = buildMapper();

        final String json = mapper.writeValueAsString(address);
        System.out.println(json);

        mapper.addMixIn(Address.class, AddressMixin.class);

        final Address deserializedUser = mapper.readValue(json, Address.class);
        System.out.println(deserializedUser);
    }

	private static ObjectMapper buildMapper() {
		ObjectMapper mapper = new ObjectMapper();
                mapper.setVisibility(mapper.getSerializationConfig()
                .getDefaultVisibilityChecker()
                .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
                .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
                .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
		return mapper;
	}
}

Here is the output:

{"city":"Hyderabad","state":"Telangana"}
Address [city=Hyderabad, state=Telangana]

References

Java Gotchas

Overloading Gotcha

Let’s consider couple of java classes

public class AirCraft {

}
public class C141AirCraft extends AirCraft {

}
public class Pilot {

    public void flyAirCraft(AirCraft airCraft) {
       System.out.println("Flying Plain Air Craft");
   }
}
public class C141Pilot extends Pilot {

    @Override
    public void flyAirCraft(AirCraft airCraft) {
      System.out.println("C141Pilot Flying Plain Air Craft");
    }

    public void flyAirCraft(C141AirCraft c141AirCraft) {
      System.out.println("C141Pilot Flying C141 Air Craft");
   }
}

What the following code would print out ?

Pilot c141Pilot = new C141Pilot();
c141Pilot.flyAirCraft(new C141AirCraft());

If you say C141Pilot Flying C141 Air Craft ? then that’s not the correct answer.

It prints the following
C141Pilot Flying Plain Air Craft

Why? As per the Java Language Specification Section 8.4.9 The signature of the method to invoked is determined at compile time, However actual method invocation on the target instance happens at run time using dynamic method lookup.

Field Shadowing Gotcha

Let’s consider couple of java classes

public class Parent {
    public String name = "Parent";
}
public class Child extends Parent {
	public String name = "Child";
}

What the following code would print out ?

Parent parent = new Child();
Child child = new Child();
System.out.println(parent.name);
System.out.println(child.name);

If you think the two output statements would print
Child
Child

Then your assumption is in correct.

As per this Java tutorial, Java data members are not Polymorphic. Parent.name and Child.name are two distinct variables, that happen to have the same name.

The output would be

Parent
Child

A Subclass variable shadows the super class variable, However then both can be accessed individually.