BufferTimeSizeWeightedFlow: Time and Size-Based Weighted Flow Aggregation in Java

This Java class implements a flow aggregation mechanism based on time and size windows with weighted elements. It aggregates elements based on a specified time interval and size limit, considering the weight of each element. This class is designed for efficient data aggregation in high-throughput scenarios.

Key Features:

  • Time-Based Aggregation: Elements are aggregated within a specified time window (e.g., 1 second, 5 minutes). This is controlled by the bufferTimeInMillis parameter.
  • Size-Based Aggregation: Elements are aggregated until a specified number of elements (size limit) is reached. This is controlled by the bufferNumberLimit parameter.
  • Weighted Aggregation: Each element has a weight associated with it, and the aggregation takes this weight into account. This is defined by the weightFunction parameter.
  • Concurrency Control: The class uses a Scheduler to handle scheduling tasks and potentially address concurrency issues. However, the exact implementation of Scheduler is not provided in this code snippet, so it's important to ensure that the Scheduler implementation is thread-safe if used in a multi-threaded environment.

Code Breakdown:

package com.taobao.powermsg3.sdk.streams;

import com.taobao.powermsg3.sdk.localserver.scheduler.Scheduler;
import com.taobao.powermsg3.sdk.util.ConstantFunction;
import io.vertx.core.Future;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.function.Function;

import static com.taobao.pubsub.util.Helper.require;

/**
 * 按照时间、大小窗口聚合
 *
 * @author 虎鸣, hepin.p@alibaba-inc.com
 */
class BufferTimeSizeWeightedFlow<T> extends PmFlow<T, List<T>> {
    private final String TIMER_KEY = UUID.randomUUID().toString();
    private final ArrayList<T> EMPTY_BUFFER = new ArrayList<>(0);

    private final boolean emitEmptyBuffer;
    private final int bufferNumberLimit;

    private final long weightLimit;

    private final Function<? super T, Long> weightFunction;

    private final Duration bufferTimeInMillis;
    private long currentWeightAccumulate;

    private final BufferAccumulator<T> bufferAccumulator;

    private final Scheduler scheduler;

    public BufferTimeSizeWeightedFlow(final int bufferNumberLimit,
                                      final long bufferTimeInMillis,
                                      final Scheduler scheduler) {
        this(bufferNumberLimit, bufferTimeInMillis, false, scheduler);
    }


    public BufferTimeSizeWeightedFlow(final int bufferNumberLimit,
                                      final long bufferTimeInMillis,
                                      final boolean emitEmptyBuffer,
                                      final Scheduler scheduler) {
        this(bufferNumberLimit, Long.MAX_VALUE, ConstantFunction.ALWAYS_ZERO, bufferTimeInMillis, emitEmptyBuffer,
            new ListBufferAccumulator<>(),
            scheduler);
    }

    public BufferTimeSizeWeightedFlow(final int bufferNumberLimit,
                                      final long weightLimit,
                                      final Function<? super T, Long> weightFunction,
                                      final long bufferTimeInMillis,
                                      final boolean emitEmptyBuffer,
                                      final BufferAccumulator<T> bufferAccumulator,
                                      final Scheduler scheduler) {
        super();
        require(bufferNumberLimit > 0, "bufferSizeLimit should > 0");
        require(bufferTimeInMillis > 1, "bufferTime should > 1ms");
        require(weightLimit >= 0, "weight limit must >= 0");
        require(weightFunction != null, "weight function should not be null.");
        require(bufferAccumulator != null, "bufferAccumulator should not be null.");
        require(scheduler != null, "scheduler should not be null.");
        this.bufferNumberLimit = bufferNumberLimit;
        this.weightLimit = weightLimit;
        this.weightFunction = weightFunction;
        this.bufferTimeInMillis = Duration.ofMillis(bufferTimeInMillis);
        this.emitEmptyBuffer = emitEmptyBuffer;
        this.bufferAccumulator = bufferAccumulator;
        this.scheduler = scheduler;
        //schedule
        scheduleNextTickWithFixDelay();
    }

    @Override
    protected void onTimer(final Object timerKey) {
        super.onTimer(timerKey);
        if (bufferAccumulator.isNotEmpty()) {
            final List<T> result = bufferAccumulator.result();
            select(result).write(Collections.unmodifiableList(result));
            bufferAccumulator.allocate(bufferNumberLimit);
        } else if (emitEmptyBuffer) {
            select(EMPTY_BUFFER).write(Collections.unmodifiableList(EMPTY_BUFFER));
        }
    }

    @Override
    protected Future<Void> onPush(final T data) {

        final long currentElemWeight = weightFunction.apply(data);
        require(currentElemWeight >= 0, "weight function should return >= 0");
        final long maybeWeightExceed = (currentWeightAccumulate + currentElemWeight) - weightLimit;
        if (maybeWeightExceed == 0) {
            bufferAccumulator.offer(data);
            final List<T> currentBuffer = bufferAccumulator.result();
            //reschedule
            scheduleNextTickWithFixDelay();
            bufferAccumulator.allocate(bufferNumberLimit);
            currentWeightAccumulate = 0;
            return select(currentBuffer).write(Collections.unmodifiableList(currentBuffer));
        } else if (maybeWeightExceed > 0) {
            final List<T> currentBuffer = bufferAccumulator.result();
            //reschedule
            scheduleNextTickWithFixDelay();
            bufferAccumulator.allocate(bufferNumberLimit);
            currentWeightAccumulate = 0;
            select(currentBuffer).write(Collections.unmodifiableList(currentBuffer));
        } else {
            currentWeightAccumulate += currentElemWeight;
        }

        bufferAccumulator.offer(data);
        if (bufferAccumulator.size() == bufferNumberLimit) {
            final List<T> currentBuffer = bufferAccumulator.result();
            //reschedule
            scheduleNextTickWithFixDelay();
            bufferAccumulator.allocate(bufferNumberLimit);
            currentWeightAccumulate = 0;
            return select(currentBuffer).write(Collections.unmodifiableList(currentBuffer));
        }

        return context.succeededFuture();
    }

    protected void scheduleNextTickWithFixDelay() {
        //取消之前的timer
        scheduler.cancel(TIMER_KEY);
        //重新调度一个timer
        scheduler.scheduleWithFixDelay(TIMER_KEY, bufferTimeInMillis, bufferTimeInMillis,
            () -> onTimer(TIMER_KEY),
            context);
    }

    @Override
    protected Future<Void> onUpstreamFinish() {
        scheduler.cancel(TIMER_KEY);
        if (bufferAccumulator.isNotEmpty()) {
            final List<T> currentBuffer = bufferAccumulator.result();
            return select(currentBuffer).write(Collections.unmodifiableList(currentBuffer));
        }
        return super.onUpstreamFinish();
    }
}

Concurrency Considerations:

The code's concurrency behavior heavily relies on the Scheduler implementation. To ensure proper concurrency in a multi-threaded environment, you need to ensure the following:

  • Thread-Safe Scheduler: The Scheduler implementation used should be thread-safe, guaranteeing that concurrent calls to scheduleWithFixDelay and cancel are handled correctly.
  • Synchronized Access to Shared Data: If BufferAccumulator, currentWeightAccumulate, or other shared data are modified by different threads, appropriate synchronization mechanisms (e.g., locks, atomic operations) should be employed to prevent data corruption.

Testing for Concurrency and Performance:

To ensure the code's correctness and performance under high concurrency, it's essential to perform thorough testing:

  • Concurrency Testing: Use tools like JUnit with a multi-threaded test runner to simulate concurrent access to the BufferTimeSizeWeightedFlow instance. Verify that the results are consistent and data integrity is maintained.
  • Performance Testing: Use benchmarks and load testing tools to measure the code's performance under high throughput. Analyze the performance bottlenecks and optimize the code as needed.

Recommendations:

  • Consider a thread-safe Scheduler implementation. Explore libraries like Quartz or Spring's TaskScheduler for proven concurrency handling.
  • Profile the code under realistic load conditions. Identify performance bottlenecks and optimize accordingly.
  • Implement thorough unit tests and integration tests to cover various scenarios, including concurrent access.

By addressing the potential concurrency issues and performing thorough testing, you can ensure that the BufferTimeSizeWeightedFlow class functions correctly and performs efficiently in a multi-threaded environment.

BufferTimeSizeWeightedFlow: A Time and Size-Based Weighted Flow Aggregation in Java

原文地址: https://www.cveoy.top/t/topic/lIfe 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录