migrator / guava-libraries-3

Guava: Google Core Libraries for Java 1.6+
0 stars 0 forks source link

Preventing thread starvation in blocking operations #23

Open migrator opened 9 years ago

migrator commented 9 years ago

I've sub-classed ListenableFuture to wrap helper functions from the Futures class to make the futures slightly more composable, however, the issue I'm now facing is preventing potential thread starvation in a fixed worker thread pool (Executors.GLOBAL) in the example below due to someone accidentally blocking in a Function or AsyncFunction (thus potentially blocking all threads in this pool).

Scala's Await.result uses "managed blocking". i.e., detect the blocking operation and temporarily spawn a new thread (see http://stackoverflow.com/a/13099594). Is there anything equivalent in Guava/Java?

Is this the reason Futures.transform has the option to use the current thread?

public MFuture flatMap(AsyncFunction<InputType, ReturnType> fn){ return new MFuture(Futures.transform(listenableFuture, fn, Executors.GLOBAL)); }

public <ReturnType> MFuture<ReturnType> map(Function<InputType, ReturnType> fn){
    return new MFuture<ReturnType>(Futures.transform(listenableFuture, fn, Executors.GLOBAL));
}

relevance: 2

migrator commented 9 years ago

summary: Not Defined

I've solved this issue by changing from a FixedThreadPool to a CachedThreadPool, which is probably ok for my scenario, but looking for suggestions.

status Not Defined creator: consiliu...@gmail.com created at: Oct 10, 2014

migrator commented 9 years ago

summary: Not Defined

The Java support for managed blocking that I'm aware of is in the JDK's ForkJoinPool. I don't believe we have anything related in Guava.

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ForkJoinPool.ManagedBlocker.html

As for applying that to your situation, I'm a bit over my head. You might try StackOverflow.

status Not Defined creator: cpov...@google.com created at: Oct 10, 2014

migrator commented 9 years ago

summary: Not Defined

Thanks, that's exactly what I was looking for.

status Not Defined creator: consiliu...@gmail.com created at: Oct 10, 2014