Created
October 23, 2014 12:54
-
-
Save kwon37xi/9f04b6e8562919c1b2e2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 쿼리의 IN 처럼 기준 값을 리스트를 받아서 처리하긴 하지만, 너무 큰 리스트는 | |
* 성능에 부담을 주기 때문에 나눠서 실행해야 할 경우, 자동으로 chunkSize에 따라 | |
* 나눠서 호출해주는 유틸리티. | |
*/ | |
public abstract class ChunkExecutionUtils { | |
public static final int DEFAULT_CHUNK_SIZE = 1000; | |
/** | |
* 청크 단위로 나눠서 코드를 실행하고 그 결과를 합쳐서 리턴한다. | |
* | |
* @param keys 키 리스트 | |
* @param chunkSize 한번에 실행할 청크의 크기 | |
* @param chunkExecutor 실제로 키 목록을 받아서 실행할 코드. | |
* @param <K> 실행시 키가 되는 파라미터 | |
* @param <V> 실행 결과 파라미터 | |
* @return 청크별로 실행한 결과로 모두 순서대로 합쳐서 리턴 | |
*/ | |
public static <K, V> List<V> executeChunk(List<K> keys, int chunkSize, ChunkExecutor<K, V> chunkExecutor) { | |
Preconditions.checkArgument(chunkSize > 0, "chunkSize must be larger than 0."); | |
Preconditions.checkNotNull(chunkExecutor, "chunkExecutor must not be null."); | |
List<V> results = Lists.newArrayList(); | |
if (CollectionUtils.isEmpty(keys)) { | |
return results; | |
} | |
int nextStartIndex = 0; | |
while (nextStartIndex < keys.size()) { | |
int toIndex = Math.min(keys.size(), nextStartIndex + chunkSize); | |
List<K> nextChunk = keys.subList(nextStartIndex, toIndex); | |
List<V> chunkResults = chunkExecutor.execute(nextChunk); | |
results.addAll(chunkResults); | |
nextStartIndex += chunkSize; | |
} | |
return results; | |
} | |
public static <K, V> List<V> executeChunk(List<K> keys, ChunkExecutor<K, V> chunkExecutor) { | |
return executeChunk(keys, DEFAULT_CHUNK_SIZE, chunkExecutor); | |
} | |
public interface ChunkExecutor<K, V> { | |
List<V> execute(List<K> chunkedKeys); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment