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 import static java.nio.file.StandardOpenOption.*; 18 import java.nio.file.*; 19 import java.io.*; 20 import java.util.*; 21 22 public class Main { 23 private static final String TEMP_FILE_NAME_PREFIX = "oflimit"; 24 private static final String TEMP_FILE_NAME_SUFFIX = ".txt"; 25 main(String[] args)26 public static void main(String[] args) throws IOException { 27 System.loadLibrary(args[0]); 28 29 setRlimitNoFile(512); 30 31 // Exhaust the number of open file descriptors. 32 List<File> files = new ArrayList<File>(); 33 List<OutputStream> streams = new ArrayList<OutputStream>(); 34 try { 35 for (int i = 0; ; i++) { 36 File file = createTempFile(); 37 files.add(file); 38 streams.add(Files.newOutputStream(file.toPath(), CREATE, APPEND)); 39 } 40 } catch (Throwable e) { 41 if (e.getMessage().contains("Too many open files")) { 42 System.out.println("Message includes \"Too many open files\""); 43 } else { 44 System.out.println("Unexpected exception:"); 45 e.printStackTrace(); 46 } 47 } 48 49 // Now try to create a new thread. 50 try { 51 Thread thread = new Thread() { 52 public void run() { 53 System.out.println("thread run."); 54 } 55 }; 56 thread.start(); 57 thread.join(); 58 } catch (Throwable e) { 59 System.out.println(e.getMessage()); 60 } 61 62 for (int i = 0; i < streams.size(); i++) { 63 streams.get(i).close(); 64 } 65 66 for (int i = 0; i < files.size(); i++) { 67 files.get(i).delete(); 68 } 69 System.out.println("done."); 70 } 71 createTempFile()72 private static File createTempFile() throws Exception { 73 try { 74 return File.createTempFile(TEMP_FILE_NAME_PREFIX, TEMP_FILE_NAME_SUFFIX); 75 } catch (IOException e) { 76 System.setProperty("java.io.tmpdir", "/data/local/tmp"); 77 try { 78 return File.createTempFile(TEMP_FILE_NAME_PREFIX, TEMP_FILE_NAME_SUFFIX); 79 } catch (IOException e2) { 80 System.setProperty("java.io.tmpdir", "/sdcard"); 81 return File.createTempFile(TEMP_FILE_NAME_PREFIX, TEMP_FILE_NAME_SUFFIX); 82 } 83 } 84 } 85 setRlimitNoFile(int value)86 public static native void setRlimitNoFile(int value); 87 } 88