---
title: "超时机制"
author: "carywei"
date: "2011-07-18T19:17:24Z"
tags: []
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2011-07-18T19:17:24Z"
id: 1127296
url: "https://carywei.iteye.com/blog/1127296"
---

static final int OP\_PENDING = 0;  
    static final int OP\_ACKNOWLEDGED = 1;  
    static final int OP\_TIMEOUT = -1;

 

 final Object mCurrentOpLock = new Object();

 

 

 

//代码调用就开始等待 在while中等待，直到 超时或者代码执行已经返回。

 boolean waitUntilOperationComplete(int token) {  
        int finalState = OP\_PENDING;  
        synchronized (mCurrentOpLock) {  
            try {  
                while ((finalState = mCurrentOperations.get(token, OP\_TIMEOUT)) == OP\_PENDING) {  
                    try {  
                        mCurrentOpLock.wait();  
                    } catch (InterruptedException e) {}  
                }  
            } catch (IndexOutOfBoundsException e) {  
                // the operation has been mysteriously cleared from our  
                // bookkeeping -- consider this a success and ignore it.  
            }  
        }  
        mBackupHandler.removeMessages(MSG\_TIMEOUT);  
        if (DEBUG) Slog.v(TAG, "operation " + Integer.toHexString(token)  
                + " complete: finalState=" + finalState);  
        return finalState == OP\_ACKNOWLEDGED;  
    }

 

 

 

public void opComplete(int token) {  
        synchronized (mCurrentOpLock) {  
            if (DEBUG) Slog.v(TAG, "opComplete: " + Integer.toHexString(token));  
            mCurrentOperations.put(token, OP\_ACKNOWLEDGED);  
            mCurrentOpLock.notifyAll();  
        }  
    }

 

 

private class BackupHandler extends Handler {  
        public BackupHandler(Looper looper) {  
            super(looper);  
        }

 

      case MSG\_TIMEOUT:  
            {  
                synchronized (mCurrentOpLock) {  
                    final int token = msg.arg1;  
                    int state = mCurrentOperations.get(token, OP\_TIMEOUT);  
                    if (state == OP\_PENDING) {  
                        if (DEBUG) Slog.v(TAG, "TIMEOUT: token=" + token);  
                        mCurrentOperations.put(token, OP\_TIMEOUT);  
                    }  
                    mCurrentOpLock.notifyAll();  
                }  
                break;  
            }  
}