• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  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 package org.apache.harmony.tests.java.util;
17 
18 import java.io.IOException;
19 import java.io.Reader;
20 import java.util.Scanner;
21 
22 import junit.framework.TestCase;
23 
24 public class ScannerParseLargeFileBenchmarkTest extends TestCase {
25 
26     /**
27      * Check whether the Scanner will exhaust all heap memory when parsing a
28      * large file.
29      */
testParseLargeFile()30     public void testParseLargeFile() throws Exception {
31         FakeLargeFile reader = new FakeLargeFile();
32         String delimiter = "\r?\n";
33         Scanner scanner = new Scanner(reader).useDelimiter(delimiter);
34 
35         while (scanner.hasNext()) {
36             scanner.next();
37         }
38         scanner.close();
39         reader.close();
40     }
41 
42     private static class FakeLargeFile extends Reader {
43         private static final char[] CONTENT = "large file!\n".toCharArray();
44         private static final int FILE_LENGTH = 192 * 1024 * 1024; // 192 MB
45 
46         private int count = 0;
47 
48         @Override
close()49         public void close() throws IOException {
50         }
51 
52         @Override
read(char[] buffer, int offset, int length)53         public int read(char[] buffer, int offset, int length) {
54             if (count >= FILE_LENGTH) {
55                 return -1;
56             }
57 
58             final int charsToRead = Math.min(FILE_LENGTH - count, length);
59             int bufferIndex = offset;
60             int contentIndex = count % CONTENT.length;
61             int charsRead = 0;
62             while (charsRead < charsToRead) {
63                 buffer[bufferIndex++] = CONTENT[contentIndex++];
64                 if (contentIndex == CONTENT.length) {
65                     contentIndex = 0;
66                 }
67                 charsRead++;
68             }
69             count += charsRead;
70             return charsToRead;
71         }
72     }
73 }
74