Обработка нескольких файлов одновременноJAVA

Программисты JAVA общаются здесь
Anonymous
Обработка нескольких файлов одновременно

Сообщение Anonymous »

Я пытаюсь переписать приложение C# на Spring Boot Java. Приложение C# создает около 150 больших файлов с помощью Parallel.ForEach
и завершается менее чем за 8 минут, тогда как приложение Java занимает около 20 минут
Программа сначала вызывает хранимую процедуру который возвращает набор результатов с информацией, необходимой для создания файла. Каждая строка результирующего набора содержит идентификатор файла, путь для сохранения файла и имя (другой процедуры хранения), которая получает
данные для помещения в файл. Каждая строка этого набора результатов сохраняется в объекте, добавленном в список.
Затем метод экспорта() просматривает список, вызывает каждую хранимую процедуру и записывает выходные данные процедуры в 2 разных файлы. (Я пытался сделать копию, но это было намного медленнее).
Как можно улучшить скорость? Я пробовал CompletableFuture и ParallelStream, но, видимо, не настроил их правильно, чтобы они были действительно многопоточными.
Метод run() выглядит следующим образом:
public void run(String... args) {
getExportFileList();
exportFileList.parallelStream().forEach( x -> { export_file.export(x); } );

```

Here are the getExportFileList() and export() methods:

```
private void getExportFileList()
{
ExportClientsIntraDaysImplementation impl = new ExportClientsIntraDaysImplementation();
String ecid = Objects.equals(exportClientID, "") ? null : exportClientID;

String connString = paths.getConfig().getConnection();
Connection connection = Sql.getConnection(Sql.getContext(connStr));
CallableStatement callableStatement = connection.prepareCall(call [dbo].[PROC_Get_Export_Clients] (?) );
int i = 0;
callableStatement.setString(++i, id);
callableStatement.execute();
ResultSet rs = callableStatement.getResultSet();

try {
if (rs != null) {
while (rs.next())
{
int rwoNUm = rs.getRow();
ExportFile exportFile = new ExportFile();
exportFile.positions = positions;
exportFile.Export_ClientID = rs.getInt("Export_ClientID");
exportFile.FileDestination = rs.getString("FileDestination").trim();
String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
exportFile.FTPDestination = rs.getString("FTPDestination").trim().replace("DATE", date);
exportFile.StoredProcedureName = rs.getString("StoredProcedure");
exportFileList.add(exportFile);

}
}
log.info("Folders created");
}
catch (Exception ex)
{
log.error("Error reading from database", ex);
}
}
```

export() method:

```
public void export(ExportFile exportFile)
{

ExportClientsIntraDaysImplementation impl = new ExportClientsIntraDaysImplementation();
String connection = positions.getConfig().getConnection();
LocalDateTime start = null;
int count = 0;
int lines = 0;
try
{

BufferedWriter writer = new BufferedWriter(new FileWriter(exportFile.FileDestination), 65536); //65536 32768
BufferedWriter ftpWriter = new BufferedWriter(new FileWriter(exportFile.FTPDestination), 65536); //65536

ResultSet posnFiles = impl.getExportPositionFiles(Integer.toString(exportFile.Export_ClientID), exportFile.StoredProcedureName, connection);
System.out.println("Start writing to files: " + LocalDateTime.now());
log.info("Start writing to file for : " + exportFile.Export_ClientID + " " + LocalDateTime.now());
if (posnFiles != null)
{
while (posnFiles.next())
{
String data = posnFiles.getString(1);
lines++;
if(data == null)
{
writer.write("");
ftpWriter.write("");
}
else
{
writer.write(data);
ftpWriter.write(data);
}
writer.write("\n");
ftpWriter.write("\n");
}
}
writer.close();
ftpWriter.close();
log.info("Stop writing " + lines + " lines to files ");
log.info("for :" + exportFile.Export_ClientID ); //+ " " + LocalDateTime.now());
}
catch (Exception ex)
{
log.error("Error reading from database", ex);
}
} //End export
```

For CompletableFuture, the differences to export() are the signature and return of a CompletableFuture.

```
return CompletableFuture.completedFuture(null);
```

Also, in another file, the TheeadPoolTaskExecutor object is created:

```
@Bean(name = "asyncExecutor")
public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(15);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(2050);
executor.setThreadNamePrefix("poolThread-");
executor.initialize();
return executor; }

```

The run() method, using CF is:
```
public void run(String... args) {
List futureList=new ArrayList();
exportFileList.forEach( x -> {futureList.add(export_file.export(x));});
}//End run

``


Подробнее здесь: https://stackoverflow.com/questions/790 ... ltaneously

Вернуться в «JAVA»