0

I have two sources, one is Kafka source and one is the custom source, I need to make a sleep custom source for one hour but I am getting below interruption.

java.lang.InterruptedException: sleep interrupted
    at java.lang.Thread.sleep(Native Method)
    at com.hulu.hiveIngestion.HiveAddPartitionThread.run(HiveAddPartitionThread.java:48)
    at org.apache.flink.streaming.api.operators.StreamSource.run(StreamSource.java:100)
    at org.apache.flink.streaming.api.operators.StreamSource.run(StreamSource.java:63)
    at org.apache.flink.streaming.runtime.tasks.SourceStreamTask$LegacySourceFunctionThread.run(SourceStreamTask.java:201)

Code:

<kafka_Source>.union(<custom_source>)

public class custom_source implements SourceFunction<String> {
public void run(SourceContext<String> ctx)  {
 while(true)
 {
  Thread.sleep(1000);
  ctx.collect("string");
 }
}
}

How to make sleep custom source while Kafka source will continue with its stream. why I am getting thread interruption exception?

1 Answers1

2

This is more a Java than Flink question. In short, you can never rely on Thread.sleep(x) to sleep for x ms. It's also important to properly support interruption or else you can not gracefully shutdown your job.

public class custom_source implements SourceFunction<String> {
    private static final Duration SLEEP_DURATION = Duration.ofHours(1);
    private volatile boolean isCanceled = false;

    public void run(SourceContext<String> ctx) {
        while (!isCanceled) {
            // 1 hour wait time
            LocalTime end = LocalTime.now().plusHours(1);
            // this loop ensures that random interruption is not prematurely closing the source
            while (LocalTime.now().compareTo(end) < 0) {
                try {
                    Thread.sleep(Duration.between(LocalTime.now(), end).toMillis());
                } catch (InterruptedException e) {
                    // swallow interruption unless source is canceled
                    if (isCanceled) {
                        Thread.interrupted();
                        return;
                    }
                }
            }
            ctx.collect("string");
        }
    }

    @Override
    public void cancel() {
        isCanceled = true;
    }
}
Arvid Heise
  • 3,524
  • 5
  • 11