1 /*
2  * Copyright (C) 2016 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 libcore.io;
18 
19 import dalvik.system.BlockGuard;
20 
21 /**
22  * Used to detect unbuffered I/O.
23  * @hide
24  */
25 public final class IoTracker {
26     private int opCount;
27     private int totalByteCount;
28     private boolean isOpen = true;
29     private Mode mode = Mode.READ;
30 
trackIo(int byteCount)31     public void trackIo(int byteCount) {
32         ++opCount;
33         totalByteCount += byteCount;
34         if (isOpen && opCount > 10 && totalByteCount < 10*512) {
35             BlockGuard.getThreadPolicy().onUnbufferedIO();
36             isOpen = false;
37         }
38     }
39 
trackIo(int byteCount, Mode mode)40     public void trackIo(int byteCount, Mode mode) {
41         if (this.mode != mode) {
42             reset();
43             this.mode = mode;
44         }
45         trackIo(byteCount);
46     }
47 
48     /**
49      * Resets the state of the IoTracker, except {@link #isOpen} as it is not required to notify
50      * again and again about the same stream.
51      * This is primarily used by RandomAccessFile to consider a case when {@link
52      * java.io.RandomAccessFile#seek seek} is called.
53      */
reset()54     public void reset() {
55         opCount = 0;
56         totalByteCount = 0;
57     }
58 
59     public enum Mode {
60         READ,
61         WRITE
62     }
63 }
64