Thread.interrupt()和java.io.InterruptedIOException

时间:2011-09-27 20:46:41

标签: java multithreading log4j java-io java.util.concurrent

我在Solaris 10上运行Java 1.5。 我的程序是一个独立的java程序,使用java并发包和log4j-1.2.12.jar来记录某些信息。主要逻辑如下

ExecutorService executor = new AppThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE), new AppThreadFactory("BSRT", true), new ThreadPoolExecutor.CallerRunsPolicy());
        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executor);
        for (final Integer id : taskList) {
            Callable<Integer> c = new Callable<Integer>() {
                public Integer call() throws Exception {
                    int newId = DB operation(id);
                    return newId;
                }
            };
            completionService.submit(c);
        }
        logger.debug("Start retrievie result");
        for (Integer id : taskList) {
            try {
                Future<Integer> future = completionService.poll(1, TimeUnit.SECONDS);               
                Integer taskId=null;
                if (future != null) {
                    logger.debug("future is obtained.");
                    taskId = future.get();
                } else {
                    logger.error("wait too long and get nothing!");
                    break;
                }
                if (taskId != null) {
                    taskIdList.add(taskId);
                }
            } catch (ExecutionException ignore) {
                // log the cause and ignore this aborted task,coninue with
                // next available task.
                logger.warn(ignore.getCause());
            } catch (InterruptedException e) {
                logger.warn("interrupted...");
                // Re-assert the thread’s interrupted status
                Thread.currentThread().interrupt();
            }
        }executor.shutdown();

在我的程序执行期间,有时(并非总是)我收到此错误...

executor.shutdown(); 
从通话super.run();返回后,

将无法中断AppThread 因为woker已经从ThreadPoolExecutor内部使用的工作集中删除了,所以执行者从那时起就没有引用AppThread。

btw:日志文件可以访问,大小足够大。

log4j:ERROR Failed to flush writer,
java.io.InterruptedIOException
       at java.io.FileOutputStream.writeBytes(Native Method)
       at java.io.FileOutputStream.write(FileOutputStream.java:260)
       at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:336)
       at sun.nio.cs.StreamEncoder$CharsetSE.implFlushBuffer(StreamEncoder.java:404)
       at sun.nio.cs.StreamEncoder$CharsetSE.implFlush(StreamEncoder.java:408)
       at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:152)
       at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:213)
       at org.apache.log4j.helpers.QuietWriter.flush(QuietWriter.java:57)
       at org.apache.log4j.WriterAppender.subAppend(WriterAppender.java:315)
       at org.apache.log4j.DailyRollingFileAppender.subAppend(DailyRollingFileAppender.java:358)
       at org.apache.log4j.WriterAppender.append(WriterAppender.java:159)
       at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:230)
       at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:65)
       at org.apache.log4j.Category.callAppenders(Category.java:203)
       at org.apache.log4j.Category.forcedLog(Category.java:388)
       at org.apache.log4j.Category.debug(Category.java:257)
       at AppThread.run( AppThread.java: 33)  

33是一行:if (debug) logger.info("Exiting " + getName());

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.log4j.Logger;

public class AppThread extends Thread {
    public static final String DEFAULT_NAME = "MyAppThread";
    private static volatile boolean debugLifecycle = false;
    private static final AtomicInteger created = new AtomicInteger();
    private static final AtomicInteger alive = new AtomicInteger();
    private static final Logger logger = Logger.getLogger(AppThread.class);
    private boolean dump = false;

    public AppThread(Runnable r) {
        this(r, DEFAULT_NAME);
    }

    public AppThread(Runnable runnable, String name) {
        super(runnable, name + "-" + created.incrementAndGet());
        logger.debug(name + "'s constructor running");
    }

    public void interrupt() {
        if (!dump) {
            super.interrupt();
        }
        if (dump) {
            logger.debug("interrupt : " + getName() + " <<<");
            Thread.dumpStack();
            logger.debug("interrupt : " + getName() + " >>>");
        }
    }

    public void run() {
        boolean debug = debugLifecycle;
        if (debug)
            logger.info("Created " + getName());
        try {
            alive.incrementAndGet();
            super.run();
            logger.debug("running!");
        } finally {
            alive.decrementAndGet();
            dump = true;
            try {
                Thread.sleep(100000);
            } catch (InterruptedException e) {
                logger.debug(e);
            }
            if (debug)
                logger.info("Exiting " + getName());
        }
    }

    public static int getThreadsCreated() {
        return created.get();
    }

    public static int getThreadsAlive() {
        return alive.get();
    }

    public static boolean getDebug() {
        return debugLifecycle;
    }

    public static void setDebug(boolean b) {
        debugLifecycle = b;
    }
}

另一个问题是,为了调试java.io.InterruptedIOException的原因,我添加了

     try {
            Thread.sleep(100000);
        } catch (InterruptedException e) {
            logger.debug(e);
        }

在AppThread的run方法的finally子句中。当在finally子句中捕获InterruptedException时,永远不会调用覆盖interrupt()方法。谁中断了AppThread?因java.io.InterruptedIOException而导致同一个人?

3 个答案:

答案 0 :(得分:7)

是:

  

执行shutdownNow   尝试停止所有正在执行的任务,停止等待任务的处理,并返回等待执行的任务列表。

     

除了尽力尝试停止处理主动执行任务之外,没有任何保证。例如,典型的实现将通过Thread.interrupt() 取消,因此任何无法响应中断的任务都可能永远不会终止。

JavaDoc

只需使用shutdown()代替shutdownNow()。当您强行调用shutdownNow()时,这是您应该期望的 - JVM会优雅地中断I / O并尽快关闭线程。

但是我会确保日志记录不是应用程序的瓶颈。只需在程序执行期间进行一些线程转储,并查看线程写入或等待I / O的频率。穷人的表现。

答案 1 :(得分:1)

中断工作线程实际上是Executor框架的功能,允许工作线程在被要求通过interrupt()时正常关闭。它记录了shutdownNow()的行为。

如果您不想这样做,请致电shutdown() - 它不会interrupt()您的工作线程,Executor将停止接受新任务。

答案 2 :(得分:0)

我有类似的问题。 我的研究到目前为止Thread.interrupt()设置了中断标志。这导致Java堆栈深处的IO操作中断。但IO方法通常不会被声明为抛出InterruptedException

而是抛出InterruptedIOException并清除线程的中断状态!。如果您编写了一个期望(捕获)IOException的工作者,则必须单独捕获InterruptedIOException并在catch子句中调用Thead.currentThread().interrupt()