I want to access the data inside the runnable objects which I have in the custom threadpool executor. If I tried to access in the before/after execute methods I am getting class cast exception. How do i resolve this scenario.
public class MyThread implements Runnable
{
String key;
public void run(){ /* Do something */}
}
public class MyExecutor extends ThreadPoolExecutor
{
@Override
protected void beforeExecute(Thread paramThread, Runnable paramRunnable)
{
MyThread mt = (mt)paramRunnable;
}
@Override
protected void afterExecute(Runnable paramRunnable, Throwable paramThrowable)
{
MyThread mt = (mt)paramRunnable;
/* Need to access "key" inside MyThread */
}
If get ClassCastException
that means you pass in Thread implementations that are not MyThread
or subclass of MyThread
also into your MyExecutor
. So in order to fix it you just do a instanceof
check before casting.
public class MyExecutor extends ThreadPoolExecutor
{
@Override
protected void beforeExecute(Thread paramThread, Runnable paramRunnable)
{
if(paramRunnable instanceof MyThread) {
MyThread mt = (MyThread)paramRunnable;
}
}
@Override
protected void afterExecute(Runnable paramRunnable, Throwable paramThrowable)
{
if(paramRunnable instanceof MyThread) {
MyThread mt = (MyThread)paramRunnable;
}
/* Need to access "key" inside MyThread */
}
The solution is to use my thread as callable, and get the response in the futuretask response. The below implementation solved my solution.
protected void afterExecute(Runnable paramRunnable, Throwable paramThrowable) {
super.afterExecute(paramRunnable, paramThrowable);
FutureTask<String> task = (FutureTask<String>) paramRunnable;
try {
String a = task.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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.