Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,10 @@
*/
package com.ibm.cloud.objectstorage.http.timers;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import com.ibm.cloud.objectstorage.SdkClientException;
import com.ibm.cloud.objectstorage.annotation.SdkInternalApi;

/**
Expand All @@ -37,7 +35,7 @@ public class TimeoutThreadPoolBuilder {
*/
public static ScheduledThreadPoolExecutor buildDefaultTimeoutThreadPool(final String name) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5, getThreadFactory(name));
safeSetRemoveOnCancel(executor);
executor.setRemoveOnCancelPolicy(true);
executor.setKeepAliveTime(5, TimeUnit.SECONDS);
executor.allowCoreThreadTimeOut(true);

Expand All @@ -58,36 +56,4 @@ public Thread newThread(Runnable r) {
}
};
}

/**
* {@link ScheduledThreadPoolExecutor#setRemoveOnCancelPolicy(boolean)} is not available in Java
* 6 so we invoke it with reflection to be able to compile against Java 6.
*
* @param executor
*/
private static void safeSetRemoveOnCancel(ScheduledThreadPoolExecutor executor) {
try {
executor.getClass().getMethod("setRemoveOnCancelPolicy", boolean.class).invoke(executor, Boolean.TRUE);
} catch (IllegalAccessException e) {
throwSetRemoveOnCancelException(e);
} catch (IllegalArgumentException e) {
throwSetRemoveOnCancelException(e);
} catch (InvocationTargetException e) {
throwSetRemoveOnCancelException(e.getCause());
} catch (NoSuchMethodException e) {
throw new SdkClientException("The request timeout feature is only available for Java 1.7 and above.");
} catch (SecurityException e) {
throw new SdkClientException("The request timeout feature needs additional permissions to function.", e);
}
}

/**
* Wrap exception caused by calling setRemoveOnCancel in a {@link SdkClientException}.
*
* @param cause
* Root cause of exception
*/
private static void throwSetRemoveOnCancelException(Throwable cause) {
throw new SdkClientException("Unable to setRemoveOnCancelPolicy for request timeout thread pool", cause);
}
}