简体   繁体   中英

Is it safe to share a stream instance among multiple threads?

I have a set of keys.

class X {
  private static String[] keys = {"k1", "k2", ... };

I have to extract values for the keys from a request. I think I can use map to extract values and create a list necessary objects in some request processing method like this:

  public void processReq(Request req) {
    ...
    Stream.of(keys).map(k-> new Pack(k, req.getHeader(k)));

But creating Stream per every request looks unnecessary task. If sharing Stream instance among multiple threads is safe, I think I can modify the code like this:

class X {
  private static Stream<String> keys = Stream.of("k1", "k2", ...);
  ...

  public void processReq(Request req) {
    ...
    keys..map(k-> new Pack(k, req.getHeader(k)));

So, is sharing Stream instance among multiple threads like this safe?

Streams are not intended to be used more than once, even in the same thread. If you want to have a collection, use a List (or an array)

 private static final List<String> keys = Arrays.asList("k1", "k2", ...);

This can be used multiple times.

List<Pack> packs = keys.stream()
                       .map(k-> new Pack(k, req.getHeader(k)))
                       .collect(Collectors.toList());

In your code, the new Pack or req.getHeader is where most of the time is spent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM