CallbackProtector.h revision 485a038f9f0f898227b8ab4218e94c5d56b6ed0b
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "utils/threads.h"
18
19//--------------------------------------------------------------------------------------------------
20namespace android {
21
22class CallbackProtector : public RefBase {
23
24public:
25    CallbackProtector();
26    virtual ~CallbackProtector();
27
28    /**
29     * Indicates whether the CallbackProtector is non-NULL and it's safe to enter the callback.
30     */
31    static bool enterCbIfOk(const sp<CallbackProtector> &protector);
32
33    /**
34     * Indicates whether it's safe to enter the callback. It would typically return false
35     * if the associated object (AudioTrack, AudioPlayer, MediaPlayer) is about to be destroyed.
36     */
37    bool enterCb();
38
39    /**
40     * This method must be paired to each call to enterCb() or enterCbIfOk(),
41     * only it returned that it is safe enter the callback;
42     */
43    void exitCb();
44
45    /**
46     * Called to signal the associated object is about to be destroyed, so whenever a callback is
47     * entered (see enterCb) it will be notified it is pointless to process the callback. This will
48     * return immediately if there are no callbacks, and will block until current callbacks exit.
49     */
50    void requestCbExitAndWait();
51
52private:
53    Mutex mLock;
54    Condition mCbExitedCondition;
55
56    bool mSafeToEnterCb;
57
58    /** Counts the number of callbacks actively locking the associated AudioPlayer */
59    unsigned int mCbCount;
60
61    // disallow "evil" constructors
62    CallbackProtector(const CallbackProtector &);
63    CallbackProtector &operator=(const CallbackProtector &);
64};
65
66} // namespace android
67