1 /*
2  * Copyright (C) 2022 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 package com.android.net.module.util.async;
18 
19 import java.io.IOException;
20 import java.util.concurrent.Executor;
21 
22 /**
23  * Manages Async IO files and scheduled alarms, and executes all related callbacks
24  * in its own thread.
25  *
26  * All callbacks of AsyncFile, Alarm and EventManager will execute on EventManager's thread.
27  *
28  * Methods of this interface can be called from any thread.
29  *
30  * @hide
31  */
32 public interface EventManager extends Executor {
33     /**
34      * Represents a scheduled alarm, allowing caller to attempt to cancel that alarm
35      * before it executes.
36      *
37      * @hide
38      */
39     public interface Alarm {
40         /** @hide */
41         public interface Listener {
onAlarm(Alarm alarm, long elapsedTimeMs)42             void onAlarm(Alarm alarm, long elapsedTimeMs);
onAlarmCancelled(Alarm alarm)43             void onAlarmCancelled(Alarm alarm);
44         }
45 
46         /**
47          * Attempts to cancel this alarm. Note that this request is inherently
48          * racy if executed close to the alarm's expiration time.
49          */
cancel()50         void cancel();
51     }
52 
53     /**
54      * Requests EventManager to manage the given file.
55      *
56      * The file descriptors are not cloned, and EventManager takes ownership of all files passed.
57      *
58      * No event callbacks are enabled by this method.
59      */
registerFile(FileHandle fileHandle, AsyncFile.Listener listener)60     AsyncFile registerFile(FileHandle fileHandle, AsyncFile.Listener listener) throws IOException;
61 
62     /**
63      * Schedules Alarm with the given timeout.
64      *
65      * Timeout of zero can be used for immediate execution.
66      */
scheduleAlarm(long timeout, Alarm.Listener callback)67     Alarm scheduleAlarm(long timeout, Alarm.Listener callback);
68 
69     /** Schedules Runnable for immediate execution. */
70     @Override
execute(Runnable callback)71     void execute(Runnable callback);
72 
73     /** Throws a runtime exception if the caller is not executing on this EventManager's thread. */
assertInThread()74     void assertInThread();
75 }
76