All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.skjolber.unzip.csv.PerThreadCsvFileEntryHandlerFactory Maven / Gradle / Ivy

package com.github.skjolber.unzip.csv;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Handler cache which limits creating new handlers to one per thread.
 *
 */

public class PerThreadCsvFileEntryHandlerFactory implements CsvLineHandlerFactory {

	protected Map>> handlers = new ConcurrentHashMap<>();

	protected CsvLineHandlerFactory factory;
	
	public PerThreadCsvFileEntryHandlerFactory(CsvLineHandlerFactory factory) {
		this.factory = factory;
	}

	@SuppressWarnings("unchecked")
	@Override
	public  CsvLineHandler getHandler(String fileName, ThreadPoolExecutor executor) {

		Map> map = handlers.get(Thread.currentThread());
		if(map == null) {
			map = new HashMap<>();
			handlers.put(Thread.currentThread(), map);
		}

		CsvLineHandler csvLineHandler = (CsvLineHandler) map.get(fileName);
		if(csvLineHandler == null) {
			csvLineHandler = factory.getHandler(fileName, executor);
			map.put(fileName, csvLineHandler);
		}
		
		return csvLineHandler;
	}

	public Set getFileNames() {
		Set result = new HashSet<>();
		
		for (Entry>> threadEntry : handlers.entrySet()) {
			for (Entry> fileEntity: threadEntry.getValue().entrySet()) {
				result.add(fileEntity.getKey());
			}
		}
		
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public  List> getHandlers(String fileName) {
		List> list = new ArrayList<>();
		
		for (Entry>> threadEntry : handlers.entrySet()) {
			for (Entry> fileEntity: threadEntry.getValue().entrySet()) {
				if(fileEntity.getKey().equals(fileName)) {
					list.add((CsvLineHandler) fileEntity.getValue());
				}
			}
		}
		
		return list;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy