001/* 002 * (C) Copyright 2017 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * bdelbosc 018 */ 019package org.nuxeo.lib.stream.pattern.consumer; 020 021import java.time.Duration; 022 023/** 024 * Describe when a batch must be flushed. 025 * 026 * @since 9.1 027 */ 028public class BatchPolicy { 029 public static final BatchPolicy NO_BATCH = builder().capacity(1).build(); 030 031 public static final BatchPolicy DEFAULT = builder().build(); 032 033 protected final int capacity; 034 035 protected final Duration threshold; 036 037 public BatchPolicy(Builder builder) { 038 capacity = builder.capacity; 039 threshold = builder.threshold; 040 } 041 042 public int getCapacity() { 043 return capacity; 044 } 045 046 public Duration getTimeThreshold() { 047 return threshold; 048 } 049 050 public static Builder builder() { 051 return new Builder(); 052 } 053 054 public static class Builder { 055 protected int capacity = 10; 056 057 protected Duration threshold = Duration.ofSeconds(10); 058 059 protected Builder() { 060 061 } 062 063 /** 064 * Set the capacity of the batch. 065 */ 066 public Builder capacity(int capacity) { 067 this.capacity = capacity; 068 return this; 069 } 070 071 /** 072 * Set the time threshold to fill a batch. 073 */ 074 public Builder timeThreshold(Duration threshold) { 075 this.threshold = threshold; 076 return this; 077 } 078 079 public BatchPolicy build() { 080 return new BatchPolicy(this); 081 } 082 083 } 084 085 @Override 086 public String toString() { 087 return "BatchPolicy{" + "capacity=" + capacity + ", threshold=" + threshold + '}'; 088 } 089}