1/* 2 * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26package sun.net; 27 28import java.net.SocketException; 29import java.util.concurrent.atomic.AtomicInteger; 30import sun.security.action.GetPropertyAction; 31 32/** 33 * Manages count of total number of UDP sockets and ensures 34 * that exception is thrown if we try to create more than the 35 * configured limit. 36 * 37 * This functionality could be put in NetHooks some time in future. 38 */ 39 40public class ResourceManager { 41 42 /* default maximum number of udp sockets per VM 43 * when a security manager is enabled. 44 * The default is 25 which is high enough to be useful 45 * but low enough to be well below the maximum number 46 * of port numbers actually available on all OSes 47 * when multiplied by the maximum feasible number of VM processes 48 * that could practically be spawned. 49 */ 50 51 private static final int DEFAULT_MAX_SOCKETS = 25; 52 private static final int maxSockets; 53 private static final AtomicInteger numSockets; 54 55 static { 56 String prop = GetPropertyAction 57 .privilegedGetProperty("sun.net.maxDatagramSockets"); 58 int defmax = DEFAULT_MAX_SOCKETS; 59 try { 60 if (prop != null) { 61 defmax = Integer.parseInt(prop); 62 } 63 } catch (NumberFormatException e) {} 64 maxSockets = defmax; 65 numSockets = new AtomicInteger(0); 66 } 67 68 public static void beforeUdpCreate() throws SocketException { 69 if (System.getSecurityManager() != null) { 70 if (numSockets.incrementAndGet() > maxSockets) { 71 numSockets.decrementAndGet(); 72 throw new SocketException("maximum number of DatagramSockets reached"); 73 } 74 } 75 } 76 77 public static void afterUdpClose() { 78 if (System.getSecurityManager() != null) { 79 numSockets.decrementAndGet(); 80 } 81 } 82} 83