Example usage for java.util.concurrent.atomic AtomicReference updateAndGet

List of usage examples for java.util.concurrent.atomic AtomicReference updateAndGet

Introduction

In this page you can find the example usage for java.util.concurrent.atomic AtomicReference updateAndGet.

Prototype

public final V updateAndGet(UnaryOperator<V> updateFunction) 

Source Link

Document

Atomically updates (with memory effects as specified by VarHandle#compareAndSet ) the current value with the results of applying the given function, returning the updated value.

Usage

From source file:org.workspace7.moviestore.controller.ShoppingCartController.java

/**
 * @param modelAndView/* ww w  .  j ava2s.  c om*/
 * @param session
 * @param response
 * @return
 */
@GetMapping("/cart/show")
public ModelAndView showCart(ModelAndView modelAndView, HttpSession session, HttpServletResponse response) {

    final String hostname = System.getenv().getOrDefault("HOSTNAME", "unknown");

    modelAndView.addObject("hostname", hostname);

    MovieCart movieCart = (MovieCart) session.getAttribute(SESSION_ATTR_MOVIE_CART);

    log.info("Showing Cart {}", movieCart);

    if (movieCart != null) {

        modelAndView.addObject("movieCart", movieCart);
        AtomicReference<Double> cartTotal = new AtomicReference<>(0.0);
        Map<String, Integer> movieItems = movieCart.getMovieItems();
        List<MovieCartItem> cartMovies = movieCart.getMovieItems().keySet().stream().map(movieId -> {
            Movie movie = movieDBHelper.query(movieId);
            int quantity = movieItems.get(movieId);
            double total = quantity * movie.getPrice();
            cartTotal.updateAndGet(aDouble -> aDouble + total);
            log.info("Movie:{} total for {} items is {}", movie, quantity, total);
            return MovieCartItem.builder().movie(movie).quantity(quantity).total(total).build();
        }).collect(Collectors.toList());
        modelAndView.addObject("cartItems", cartMovies);
        modelAndView.addObject("cartCount", cartMovies.size());
        modelAndView.addObject("cartTotal",
                "" + DecimalFormat.getCurrencyInstance(Locale.US).format(cartTotal.get()));
        modelAndView.setViewName("cart");

    } else {
        modelAndView.setViewName("redirect:/");
    }
    return modelAndView;
}