@artemfisher

Разница между Callable и DeferredResult?

Chat-gpt пишет:
DeferredResult позволяет контроллеру продолжать выполнение после отправки ответа клиенту, а Callable возвращает результат в виде Future, который должен быть проверен клиентом для получения результата.

По факту заметил, что с DiferredRestult могу указывать сам пул потоков, а с Callable нет.
Это единственная разница или еще есть какие-то?

DiferredResult
@PostMapping("/search")
	public DeferredResult<String> search(@RequestParam("searchWord") String searchWord, Model model, HttpSession session)
	{
		DeferredResult<String> result = new DeferredResult<>();
		ExecutorService executor = Executors.newSingleThreadExecutor();
		
		executor.submit(()->
		{
		
			List<Catalog> catalogs = repo.getAllCatalogs();
			
			List<Product> allProducts = new ArrayList<>();
			
			for(Catalog catalog : catalogs)
			{
				List<Product> products = repo.getProductsByCatalog(catalog);	
				
				allProducts.addAll(products);
			}
			
			allProducts.removeIf(o->!o.getName().toLowerCase().contains(searchWord.toLowerCase()));
			
			List<ProductForSearch> products = new ArrayList<>();
			
			for(Product prod:allProducts)
				products.add(
						new ProductForSearch(
								prod.getId(),
								prod.getName(),
								Base64.getEncoder().encodeToString(prod.getImages().get().get(0))								
								)
						);
			
			model.addAttribute("products", products);
			
			User user;
			if(session.getAttribute("user")==null)
				user = new User();
			else
				user = (User) session.getAttribute("user");
			
			model.addAttribute("user", user);
			
			result.setResult("searchResult");
		});		
		return result;		
	}


Callable
@GetMapping("/favourites")
	public Callable<String> showFavourites(HttpSession session,Model model)
	{
		User user = (User) session.getAttribute("user");
		
		Callable<String> callable = ()->
		{
			List<Product> products = repo.getFavourites(user.getId());
			
			List<ProductForSearch> prods = new ArrayList<>();
			
			for(Product product:products)
				prods.add(
						new ProductForSearch(
								product.getId(),
								product.getName(),
								Base64.getEncoder().encodeToString(product.getImages().get().get(0))
								)
						);
			model.addAttribute("products", prods);
			model.addAttribute(user);
			
			return "user/favourites";			
		};
		
		return callable;
	}
  • Вопрос задан
  • 105 просмотров
Пригласить эксперта
Ответы на вопрос 1
xez
@xez Куратор тега Java
TL Junior Roo
Зачем нужен чат-гпт, когда есть документация?

DeferredResult provides an alternative to using a Callable for asynchronous request processing. While a Callable is executed concurrently on behalf of the application, with a DeferredResult the application can produce the result from a thread of its choice.
Subclasses can extend this class to easily associate additional data or behavior with the DeferredResult. For example, one might want to associate the user used to create the DeferredResult by extending the class and adding an additional property for the user. In this way, the user could easily be accessed later without the need to use a data structure to do the mapping.
An example of associating additional behavior to this class might be realized by extending the class to implement an additional interface. For example, one might want to implement Comparable so that when the DeferredResult is added to a PriorityQueue it is handled in the correct order.


По факту заметил, что с DiferredRestult могу указывать сам пул потоков, а с Callable нет.

Грубо говоря, да, разница в этом.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽
28 апр. 2024, в 19:54
2000 руб./за проект
28 апр. 2024, в 19:54
5000 руб./за проект
28 апр. 2024, в 19:44
10000 руб./за проект