Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it normal to loose The Java EE Request Scope when using Java 8 parallel Stream?

Tags:

At our company we are developing a quasi standard REST service running within wildfly 10.1. Each request owns a tenant header which will be intercepted by a filter and the tenant information will be stored within a @RequestScoped bean for later use inside the rest or service layer. So far so good. Now we found out that some code inside a service was using a Java 8 parallel stream and failed to use the @RequestScoped bean to lookup the current tenant. We verified this several times. Using non parallel streams solved this issue for us.

Is this normal behaviour? We are really confused that using standard Java 8 features breaks our expected container behaviour..

Are there any other such culprits we need to care of?

like image 846
Gerrit Avatar asked Apr 25 '17 09:04

Gerrit


People also ask

What is the disadvantage of parallel stream in Java 8?

Parallel Streams can actually slow you down It breaks them into subproblems which then run on separate threads for processing, these can go to different cores and then get combined when they're done. This all happens under the hood using the fork/join framework.

When we should not use parallel stream?

Similarly, don't use parallel if the stream is ordered and has much more elements than you want to process, e.g. This may run much longer because the parallel threads may work on plenty of number ranges instead of the crucial one 0-100, causing this to take very long time.

What is difference between parallel stream and normal stream in Java 8?

Normally any java code has one stream of processing, where it is executed sequentially. Whereas by using parallel streams, we can divide the code into multiple streams that are executed in parallel on separate cores and the final result is the combination of the individual outcomes.

Is parallel stream safe to use?

It is safe to use a non-concurrent collector in a collect operation of a parallel stream.


1 Answers

It seems than parallel will spawn threads even in a managed context.

However RequestScoped is handled using a ThreadLocal (We are here still in the good old multi-threaded model ie. an http Request = 1 thread).

So yes it's normal

like image 104
Gab Avatar answered Sep 21 '22 10:09

Gab