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

最近项目出现在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

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值