Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving to database in stream pipeline

As per the documentation on Oracle's website:

Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.

Does this include saving elements of the stream to a database?

Imagine the following (pseudo) code:

public SavedCar saveCar(Car car) {
  SavedCar savedCar = this.getDb().save(car);
  return savedCar;
}

public List<SavedCars> saveCars(List<Car> cars) {
  return cars.stream()
           .map(this::saveCar)
           .collect(Collectors.toList());
}

What are the unwanted effects opposed to this implementation:

public SavedCar saveCar(Car car) {
  SavedCar savedCar = this.getDb().save(car);
  return savedCar;
}

public List<SavedCars> saveCars(List<Car> cars) {
  List<SavedCars> savedCars = new ArrayList<>();
  for (Cat car : cars) {
    savedCars.add(this.saveCar(car));
  }
  return savedCars.
}
like image 924
Titulum Avatar asked Jan 24 '20 15:01

Titulum


People also ask

Can we store data in stream API?

No storage. Streams don't have storage for values; they carry values from a source (which could be a data structure, a generating function, an I/O channel, etc) through a pipeline of computational steps.

Do streams store data?

A stream does not store data and, in that sense, is not a data structure.

Are streams stored in memory?

This lets us take advantage of one of the key differences between a Stream and a Collection in Java – while Collections represent a set of data stored entirely in memory, Streams are simply storage-agnostic series of data.

Are streams better than for loops?

If you have a small list, loops perform better. If you have a huge list, a parallel stream will perform better. Purely thinking in terms of performance, you shouldn't use a for-each loop with an ArrayList, as it creates an extra Iterator instance that you don't need (for LinkedList it's a different matter).


1 Answers

The absolute easiest example is:

cars.stream()
    .map(this:saveCar)
    .count()

In this case, from java-9 and up, map will not be executed; since you do not need it to know the count, at all.

There are other multiple cases where side effects would cause you lots of pain; under certain conditions.

like image 150
Eugene Avatar answered Oct 11 '22 05:10

Eugene