android-24中DatagramSocket的坑,以及synchronized的用法详解

来源:互联网 发布:不基于比较的排序算法 编辑:程序博客网 时间:2024/05/16 12:48

最近项目出现在android 7.0 的设备上出现anr,通过排除发现是我用的第三方的jar 中在使用DatagramSocket 关闭链接的时候如下:

 if (datagramSocket != null) {            datagramSocket.disconnect();            datagramSocket.close();        }

因为这个编写的时候使用的是android 22的sdk 中的DatagramSocket ,其中disconnect源码如下:

    /**     * Disconnects this UDP datagram socket from the remote host. This method     * called on an unconnected socket does nothing.     */    public void disconnect() {        if (isClosed() || !isConnected()) {            return;        }        impl.disconnect();        address = null;        port = -1;        isConnected = false;    }

没啥毛病。但是在android 24 中DatagramSocket 的disconnect源码被修改如下:

    /**     * Disconnects the socket. If the socket is closed or not connected,     * then this method has no effect.     *     * @see #connect     */    public void disconnect() {        synchronized (this) {            if (isClosed())                return;            if (connectState == ST_CONNECTED) {                impl.disconnect ();            }            connectedAddress = null;            connectedPort = -1;            connectState = ST_NOT_CONNECTED;        }    }

很明显加了一个同步锁,这个就很致命了。我们再看下receive方法的源码:

   public synchronized void receive(DatagramPacket p) throws IOException {        synchronized (p) {            if (!isBound())                bind(new InetSocketAddress(0));            // ----- BEGIN android -----            if (pendingConnectException != null) {                throw new SocketException("Pending connect failure", pendingConnectException);            }            // ----- END android -----            if (connectState == ST_NOT_CONNECTED) {

很明显这个方法也是同步的,我们知道在sokect没有被关闭的时候我们receive方法应该是一直执行的,因为我们一般socket通信的时候数据是一直接受的。除非在关闭以后。所以最上面那段第三方sdk再操作的时候就出了问题,直接去断掉连接,然而此时正在接收,那么就造成了断链的代码得不到执行,而此时也没有人再去主动断开连接,这就造成了死锁。导致程序anr。我们应该在断链前,先关闭socket,这样receive代码就会终止,此时断开连接也不会造成一直等待的情况了。
代码修改如下:

if (datagramSocket != null) {            if (!datagramSocket.isClosed(){                datagramSocket.close();            }            datagramSocket.disconnect();            }

所以针对android 24 中的sokect使用一定要记住先关闭再断链。不然就很容易死锁。
synchronized的用法请看下篇http://blog.csdn.net/qq_35522272/article/details/54315954

0 0
原创粉丝点击