0

我在 Android 的 asmack 库中遇到了一个奇怪的问题。该库使用 ExecutorService 来解析传入的数据包,如下所示:

private ExecutorService listenerExecutor;

listenerExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() {

        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(runnable,
                    "Smack Listener Processor (" + connection.connectionCounterValue + ")");
            thread.setDaemon(true);
            return thread;
        }
    });

(...)

listenerExecutor.submit(new ListenerNotification(packet));

(...)

/**
 * A runnable to notify all listeners of a packet.
 */
private class ListenerNotification implements Runnable {

    private Packet packet;

    public ListenerNotification(Packet packet) {
        this.packet = packet;
    }

    public void run() {
        for (ListenerWrapper listenerWrapper : connection.recvListeners.values()) {
            listenerWrapper.notifyListener(packet);
        }
    }
}

一切正常,直到调用 submit() 方法时,也调用了 ListenerNotification 的构造函数,但不再调用 ListenerNotification 中的 run() 方法。

这可能是什么原因?ExecutorService 中是否存在一些可能导致调用提交被忽略的机制?

4

1 回答 1

0

正如所料,错误在我这边。

我在我的代码中实现了一个名册数据包侦听器并覆盖了 processPacket 方法:

@Override
public void processPacket(Packet packet) {
    if (packet instanceof RosterPacket) {
        RosterPacket rosterPacket = (RosterPacket) packet;
        Logger.d(LOGTAG, "Initial roster packet received: " + rosterPacket.getRosterItemCount());
        mConnection.removePacketListener(this);
        fireOnInitialRosterPacketReceived(rosterPacket);
    }
}

但是,我的内部监听器调用方法引入了一个无限循环:

private void fireOnInitialRosterPacketReceived(RosterPacket rosterPacket) {
    Iterator<SessionListener> it = mSessionListeners.iterator();
    while (it.hasNext()) {
        // it.next().onInitialRosterPacketReceived(mConnection,
        // rosterPacket);
    }
}

这阻止了执行程序启动的线程,以便随后的提交调用不会再次触发该线程。

于 2013-04-08T11:02:23.290 回答