diff options
author | Xiao Ma <xiaom@google.com> | 2019-10-17 15:54:06 +0900 |
---|---|---|
committer | Xiao Ma <xiaom@google.com> | 2019-10-17 15:54:06 +0900 |
commit | df4c156e6ef04454cc99087e75f570625d37ed70 (patch) | |
tree | 1f88dd4ef89dfdb862e7385b625b34a3eb81c097 /src/android/net/util/FdEventsReader.java | |
parent | 3c9f687c97393a15d238a3272f62c595052e6b2e (diff) |
Optimize FdEventsReader to make it safer to use.
Update the start() and createAndRegisterFd() to boolean type, to make
sure we won't return null socket when failing to create socket.
Throwing IllegalStateException if any caller is calling the FdEventsReader#
start/stop from the different thread, to make it immediately obvious.
Bug: None
Test: atest NetworkStackTests
Change-Id: I398b24da34b8fc9da7e8a9d07508c4d731c4a437
Diffstat (limited to 'src/android/net/util/FdEventsReader.java')
-rw-r--r-- | src/android/net/util/FdEventsReader.java | 32 |
1 files changed, 13 insertions, 19 deletions
diff --git a/src/android/net/util/FdEventsReader.java b/src/android/net/util/FdEventsReader.java index 1380ea7..e82c69b 100644 --- a/src/android/net/util/FdEventsReader.java +++ b/src/android/net/util/FdEventsReader.java @@ -63,7 +63,6 @@ import java.io.IOException; * the Handler constructor argument is associated. * * @param <BufferType> the type of the buffer used to read data. - * @hide */ public abstract class FdEventsReader<BufferType> { private static final int FD_EVENTS = EVENT_INPUT | EVENT_ERROR; @@ -93,27 +92,21 @@ public abstract class FdEventsReader<BufferType> { } /** Start this FdEventsReader. */ - public void start() { - if (onCorrectThread()) { - createAndRegisterFd(); - } else { - mHandler.post(() -> { - logError("start() called from off-thread", null); - createAndRegisterFd(); - }); + public boolean start() { + if (!onCorrectThread()) { + throw new IllegalStateException("start() called from off-thread"); } + + return createAndRegisterFd(); } /** Stop this FdEventsReader and destroy the file descriptor. */ public void stop() { - if (onCorrectThread()) { - unregisterAndDestroyFd(); - } else { - mHandler.post(() -> { - logError("stop() called from off-thread", null); - unregisterAndDestroyFd(); - }); + if (!onCorrectThread()) { + throw new IllegalStateException("stop() called from off-thread"); } + + unregisterAndDestroyFd(); } @NonNull @@ -178,8 +171,8 @@ public abstract class FdEventsReader<BufferType> { */ protected void onStop() {} - private void createAndRegisterFd() { - if (mFd != null) return; + private boolean createAndRegisterFd() { + if (mFd != null) return true; try { mFd = createFd(); @@ -189,7 +182,7 @@ public abstract class FdEventsReader<BufferType> { mFd = null; } - if (mFd == null) return; + if (mFd == null) return false; mQueue.addOnFileDescriptorEventListener( mFd, @@ -205,6 +198,7 @@ public abstract class FdEventsReader<BufferType> { return FD_EVENTS; }); onStart(); + return true; } private boolean isRunning() { |