Ilya Zharkov Ilya Zharkov - 6 days ago 5
Java Question

Java Spring Async performance

We have a service that writes some data to a file. New file per request. For example:

GET http://service.somecompany.com/save/{data}


This request will create new file
/var/files/{random-name}.txt
.

Service is built with @Async to avoid clients to wait while file is writing. Please, see code examples:

@Controller
public class SomeController {

@Autowired
private SomeService someService;

@RequestMapping(value = "/save/{data}", method = RequestMethod.GET)
public @ResponseBody
String add(@PathVariable("data") String data) {
someService.saveData(data);
return "Ok!";
}
}


SomeService implementation:

@Service
public class SomeServiceImpl implements SomeService {

@Async
public Future<Boolean> saveData(String data) {
// file saving with BufferedWriter ...
return new AsyncResult<Boolean>(successful);
}
}


Currently each request will create new thread. But if I will send 100 000 requests for data saving - they will create the maximum available number of threads. That will be writing data too slowly.
Maybe better to limit threads number:

<task:annotation-driven executor="taskExecutor" />
<bean id="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean">
<property name="corePoolSize" value="100" />
<property name="maxPoolSize" value="250" />
<property name="keepAliveSeconds" value="60" />
</bean>


But if to limit - which size to choose? Or maybe it is real to somehow differently increase performance? What do you think?

Answer

Disk IO is faster when done sequentially (especially on non-SSD drives, I think that's the case too with SSD). If your task doesn't do anything other than write to the disk (no computation which would benefit from multi-threading), I'd use only one thread.

Comments