I am trying to run the files uploaded through antivirus and want to run each file in a separate thread. I have written method like below
@Transactional( rollbackFor = DataException.class )
public void throwExceptionIfFilesIsAMalware( MultipartFile[] files ) throws DataException
{
try
{
NullEmptyUtils.throwExceptionIfInputIsNullOrEmpty(files, GeneralConstants.FILE_NOT_FOUND);
for( MultipartFile file : files )
{
Future<Boolean> future = throwExceptionIfFileIsAMalware(file);
}
}
catch( DataException e )
{
log.error(GeneralConstants.ERROR, e);
throw e;
}
catch( Exception e )
{
log.error(GeneralConstants.ERROR, e);
throw new DataException(GeneralConstants.EXCEPTION, GeneralConstants.SOMETHING_WENT_WRONG,
HttpStatus.BAD_REQUEST);
}
}
@Async
public Future<Boolean> throwExceptionIfFileIsAMalware( MultipartFile file ) throws DataException
{
try
{
NullEmptyUtils.throwExceptionIfInputIsNull(file, GeneralConstants.FILE_NOT_FOUND);
byte[] scannedResult = clamAVClient.scan(new BufferedInputStream(file.getInputStream()));
if( !ClamAVClient.isCleanReply(scannedResult) )
{
throw new DataException(GeneralConstants.EXCEPTION,
GeneralConstants.MALWARE_EXCEPTION + GeneralConstants.SINGLE_SPACE_STRING + file.getName(),
HttpStatus.BAD_REQUEST);
}
return new AsyncResult<>(true);
}
catch( IOException e )
{
log.error(GeneralConstants.ERROR, e);
throw new DataException(GeneralConstants.EXCEPTION, GeneralConstants.FILE_IO_EXCEPTION,
HttpStatus.BAD_REQUEST);
}
catch( DataException e )
{
log.error(GeneralConstants.ERROR, e);
throw e;
}
catch( Exception e )
{
log.error(GeneralConstants.ERROR, e);
throw new DataException(GeneralConstants.EXCEPTION, GeneralConstants.SOMETHING_WENT_WRONG,
HttpStatus.BAD_REQUEST);
}
}
I want the first method which is calling the second Async method to wait till all the threads are finished.
But if I call future.get() inside the loop it will not parallelly run all the files in a thread. It will start to wait for each file to be processed in a separate thread.
How should I handle this?
Thank you
future.thenApply.