1

I am currently developing a Java EE application which will be deployed on a Payara server 4. The payara server works on host 1 and there are also 2 instances (host 1 and host 2) available as a Payara cluster.

The problem which I have is, if we schedule a task in the singleton class, then the task will be executed thrice at the same time. The question is 2-fold.

  • Why does this phenomenon happen?
  • How can I avoid such multiple execution?

The entry point looks like this. (Not the whole.)

@ApplicationScoped
@Singleton
public class StartClass {
    public void StartClass() {}
    public void init(@Observes @Initialized(ApplicationScoped.class) ServletContext) throws ... { ... }

    @Schedule(hour="*", minute="0", persistent=false)
    public void runJob() {
        MyClass my_class = new MyClass();
        my_class.do_the_job();
    }
}

Here the scheduled task which I mentioned above is my_class.do_the_job(). This method is just to insert a line into a DB and the source code is very similar to this tutorial and has several System.out.println("DO_THE_JOB"). The target table has a column which is automatically filled with the inserted timestamp. I also put an information about the host with System.getenv("HOST"). And the result is that we insert three rows every hour: 2 rows from host 1 and 1 row from host 2. But the result of println() can be found once in the log file.

Notes:

  • Usage of JTA is not the point. I would like to understand the behaviour of the application and the cluster.
  • Java version is 8
  • If there should be another relevant part, let me know.
Christoph John
  • 3,003
  • 2
  • 13
  • 23
H. Shindoh
  • 906
  • 9
  • 23

2 Answers2

4

In the JEE spec there is no way to have a @Singleton which is cluster-wide.

One possible option to get around this is to use the Payara-specific clustered singleton with the additional @Clustered annotation. It is available starting from Payara 4.182.

Read more about it here Payara clustered singleton

Christoph John
  • 3,003
  • 2
  • 13
  • 23
0

Why does this phenomenon happen?

Simply because Singleton beans are not clusterable. Meaning that each node of the cluster has its own instance of StartClass. You may find additional useful information on a similar SO question.

How can I avoid such multiple execution?

With your current setup, you can't. What you possibly need is a scheduler which supports clustering. A popular option is quartz-scheduler which supports clustering.

leopal
  • 4,711
  • 1
  • 25
  • 35