CompileJavaPackages.java revision 3265:b7583d50f67d
1/* 2 * Copyright (c) 2012, 2016, 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 com.sun.tools.sjavac; 27 28import java.io.File; 29import java.io.IOException; 30import java.io.Writer; 31import java.net.URI; 32import java.util.ArrayList; 33import java.util.Arrays; 34import java.util.Collections; 35import java.util.HashMap; 36import java.util.List; 37import java.util.Map; 38import java.util.Random; 39import java.util.Set; 40import java.util.concurrent.Callable; 41import java.util.concurrent.ExecutionException; 42import java.util.concurrent.ExecutorService; 43import java.util.concurrent.Executors; 44import java.util.concurrent.Future; 45import java.util.regex.Pattern; 46import java.util.stream.Stream; 47 48import com.sun.tools.sjavac.comp.CompilationService; 49import com.sun.tools.sjavac.options.Options; 50import com.sun.tools.sjavac.pubapi.PubApi; 51import com.sun.tools.sjavac.server.CompilationSubResult; 52import com.sun.tools.sjavac.server.SysInfo; 53 54/** 55 * This transform compiles a set of packages containing Java sources. 56 * The compile request is divided into separate sets of source files. 57 * For each set a separate request thread is dispatched to a javac server 58 * and the meta data is accumulated. The number of sets correspond more or 59 * less to the number of cores. Less so now, than it will in the future. 60 * 61 * <p><b>This is NOT part of any supported API. 62 * If you write code that depends on this, you do so at your own 63 * risk. This code and its internal interfaces are subject to change 64 * or deletion without notice.</b></p> 65 */ 66public class CompileJavaPackages implements Transformer { 67 68 // The current limited sharing of data between concurrent JavaCompilers 69 // in the server will not give speedups above 3 cores. Thus this limit. 70 // We hope to improve this in the future. 71 final static int limitOnConcurrency = 3; 72 73 Options args; 74 75 public void setExtra(String e) { 76 } 77 78 public void setExtra(Options a) { 79 args = a; 80 } 81 82 public boolean transform(final CompilationService sjavac, 83 Map<String,Set<URI>> pkgSrcs, 84 final Set<URI> visibleSources, 85 Map<String,Set<String>> oldPackageDependents, 86 URI destRoot, 87 final Map<String,Set<URI>> packageArtifacts, 88 final Map<String,Map<String, Set<String>>> packageDependencies, 89 final Map<String,Map<String, Set<String>>> packageCpDependencies, 90 final Map<String, PubApi> packagePubapis, 91 final Map<String, PubApi> dependencyPubapis, 92 int debugLevel, 93 boolean incremental, 94 int numCores) { 95 96 Log.debug("Performing CompileJavaPackages transform..."); 97 98 boolean rc = true; 99 boolean concurrentCompiles = true; 100 101 // Fetch the id. 102 final String id = String.valueOf(new Random().nextInt()); 103 // Only keep portfile and sjavac settings.. 104 //String psServerSettings = Util.cleanSubOptions(Util.set("portfile","sjavac","background","keepalive"), sjavac.serverSettings()); 105 106 SysInfo sysinfo = sjavac.getSysInfo(); 107 int numMBytes = (int)(sysinfo.maxMemory / ((long)(1024*1024))); 108 Log.debug("Server reports "+numMBytes+"MiB of memory and "+sysinfo.numCores+" cores"); 109 110 if (numCores <= 0) { 111 // Set the requested number of cores to the number of cores on the server. 112 numCores = sysinfo.numCores; 113 Log.debug("Number of jobs not explicitly set, defaulting to "+sysinfo.numCores); 114 } else if (sysinfo.numCores < numCores) { 115 // Set the requested number of cores to the number of cores on the server. 116 Log.debug("Limiting jobs from explicitly set "+numCores+" to cores available on server: "+sysinfo.numCores); 117 numCores = sysinfo.numCores; 118 } else { 119 Log.debug("Number of jobs explicitly set to "+numCores); 120 } 121 // More than three concurrent cores does not currently give a speedup, at least for compiling the jdk 122 // in the OpenJDK. This will change in the future. 123 int numCompiles = numCores; 124 if (numCores > limitOnConcurrency) numCompiles = limitOnConcurrency; 125 // Split the work up in chunks to compiled. 126 127 int numSources = 0; 128 for (String s : pkgSrcs.keySet()) { 129 Set<URI> ss = pkgSrcs.get(s); 130 numSources += ss.size(); 131 } 132 133 int sourcesPerCompile = numSources / numCompiles; 134 135 // For 64 bit Java, it seems we can compile the OpenJDK 8800 files with a 1500M of heap 136 // in a single chunk, with reasonable performance. 137 // For 32 bit java, it seems we need 1G of heap. 138 // Number experimentally determined when compiling the OpenJDK. 139 // Includes space for reasonably efficient garbage collection etc, 140 // Calculating backwards gives us a requirement of 141 // 1500M/8800 = 175 KiB for 64 bit platforms 142 // and 1G/8800 = 119 KiB for 32 bit platform 143 // for each compile..... 144 int kbPerFile = 175; 145 String osarch = System.getProperty("os.arch"); 146 String dataModel = System.getProperty("sun.arch.data.model"); 147 if ("32".equals(dataModel)) { 148 // For 32 bit platforms, assume it is slightly smaller 149 // because of smaller object headers and pointers. 150 kbPerFile = 119; 151 } 152 int numRequiredMBytes = (kbPerFile*numSources)/1024; 153 Log.debug("For os.arch "+osarch+" the empirically determined heap required per file is "+kbPerFile+"KiB"); 154 Log.debug("Server has "+numMBytes+"MiB of heap."); 155 Log.debug("Heuristics say that we need "+numRequiredMBytes+"MiB of heap for all source files."); 156 // Perform heuristics to see how many cores we can use, 157 // or if we have to the work serially in smaller chunks. 158 if (numMBytes < numRequiredMBytes) { 159 // Ouch, cannot fit even a single compile into the heap. 160 // Split it up into several serial chunks. 161 concurrentCompiles = false; 162 // Limit the number of sources for each compile to 500. 163 if (numSources < 500) { 164 numCompiles = 1; 165 sourcesPerCompile = numSources; 166 Log.debug("Compiling as a single source code chunk to stay within heap size limitations!"); 167 } else if (sourcesPerCompile > 500) { 168 // This number is very low, and tuned to dealing with the OpenJDK 169 // where the source is >very< circular! In normal application, 170 // with less circularity the number could perhaps be increased. 171 numCompiles = numSources / 500; 172 sourcesPerCompile = numSources/numCompiles; 173 Log.debug("Compiling source as "+numCompiles+" code chunks serially to stay within heap size limitations!"); 174 } 175 } else { 176 if (numCompiles > 1) { 177 // Ok, we can fit at least one full compilation on the heap. 178 float usagePerCompile = (float)numRequiredMBytes / ((float)numCompiles * (float)0.7); 179 int usage = (int)(usagePerCompile * (float)numCompiles); 180 Log.debug("Heuristics say that for "+numCompiles+" concurrent compiles we need "+usage+"MiB"); 181 if (usage > numMBytes) { 182 // Ouch it does not fit. Reduce to a single chunk. 183 numCompiles = 1; 184 sourcesPerCompile = numSources; 185 // What if the relationship betweem number of compile_chunks and num_required_mbytes 186 // is not linear? Then perhaps 2 chunks would fit where 3 does not. Well, this is 187 // something to experiment upon in the future. 188 Log.debug("Limiting compile to a single thread to stay within heap size limitations!"); 189 } 190 } 191 } 192 193 Log.debug("Compiling sources in "+numCompiles+" chunk(s)"); 194 195 // Create the chunks to be compiled. 196 final CompileChunk[] compileChunks = createCompileChunks(pkgSrcs, oldPackageDependents, 197 numCompiles, sourcesPerCompile); 198 199 if (Log.isDebugging()) { 200 int cn = 1; 201 for (CompileChunk cc : compileChunks) { 202 Log.debug("Chunk "+cn+" for "+id+" ---------------"); 203 cn++; 204 for (URI u : cc.srcs) { 205 Log.debug(""+u); 206 } 207 } 208 } 209 210 long start = System.currentTimeMillis(); 211 212 // Prepare compilation calls 213 List<Callable<CompilationSubResult>> compilationCalls = new ArrayList<>(); 214 final Object lock = new Object(); 215 for (int i = 0; i < numCompiles; i++) { 216 CompileChunk cc = compileChunks[i]; 217 if (cc.srcs.isEmpty()) { 218 continue; 219 } 220 221 String chunkId = id + "-" + String.valueOf(i); 222 Log log = Log.get(); 223 compilationCalls.add(() -> { 224 Log.setLogForCurrentThread(log); 225 CompilationSubResult result = sjavac.compile("n/a", 226 chunkId, 227 args.prepJavacArgs(), 228 Collections.<File>emptyList(), 229 cc.srcs, 230 visibleSources); 231 synchronized (lock) { 232 Util.getLines(result.stdout).forEach(Log::info); 233 Util.getLines(result.stderr).forEach(Log::error); 234 } 235 return result; 236 }); 237 } 238 239 // Perform compilations and collect results 240 List<CompilationSubResult> subResults = new ArrayList<>(); 241 List<Future<CompilationSubResult>> futs = new ArrayList<>(); 242 ExecutorService exec = Executors.newFixedThreadPool(concurrentCompiles ? compilationCalls.size() : 1); 243 for (Callable<CompilationSubResult> compilationCall : compilationCalls) { 244 futs.add(exec.submit(compilationCall)); 245 } 246 for (Future<CompilationSubResult> fut : futs) { 247 try { 248 subResults.add(fut.get()); 249 } catch (ExecutionException ee) { 250 Log.error("Compilation failed: " + ee.getMessage()); 251 Log.error(ee); 252 } catch (InterruptedException ie) { 253 Log.error("Compilation interrupted: " + ie.getMessage()); 254 Log.error(ie); 255 Thread.currentThread().interrupt(); 256 } 257 } 258 exec.shutdownNow(); 259 260 // Process each sub result 261 for (CompilationSubResult subResult : subResults) { 262 for (String pkg : subResult.packageArtifacts.keySet()) { 263 Set<URI> pkgArtifacts = subResult.packageArtifacts.get(pkg); 264 packageArtifacts.merge(pkg, pkgArtifacts, Util::union); 265 } 266 267 for (String pkg : subResult.packageDependencies.keySet()) { 268 packageDependencies.putIfAbsent(pkg, new HashMap<>()); 269 packageDependencies.get(pkg).putAll(subResult.packageDependencies.get(pkg)); 270 } 271 272 for (String pkg : subResult.packageCpDependencies.keySet()) { 273 packageCpDependencies.putIfAbsent(pkg, new HashMap<>()); 274 packageCpDependencies.get(pkg).putAll(subResult.packageCpDependencies.get(pkg)); 275 } 276 277 for (String pkg : subResult.packagePubapis.keySet()) { 278 packagePubapis.merge(pkg, subResult.packagePubapis.get(pkg), PubApi::mergeTypes); 279 } 280 281 for (String pkg : subResult.dependencyPubapis.keySet()) { 282 dependencyPubapis.merge(pkg, subResult.dependencyPubapis.get(pkg), PubApi::mergeTypes); 283 } 284 285 // Check the return values. 286 if (subResult.returnCode != 0) { 287 rc = false; 288 } 289 } 290 291 long duration = System.currentTimeMillis() - start; 292 long minutes = duration/60000; 293 long seconds = (duration-minutes*60000)/1000; 294 Log.debug("Compilation of "+numSources+" source files took "+minutes+"m "+seconds+"s"); 295 296 return rc; 297 } 298 299 /** 300 * Split up the sources into compile chunks. If old package dependents information 301 * is available, sort the order of the chunks into the most dependent first! 302 * (Typically that chunk contains the java.lang package.) In the future 303 * we could perhaps improve the heuristics to put the sources into even more sensible chunks. 304 * Now the package are simple sorted in alphabetical order and chunked, then the chunks 305 * are sorted on how dependent they are. 306 * 307 * @param pkgSrcs The sources to compile. 308 * @param oldPackageDependents Old package dependents, if non-empty, used to sort the chunks. 309 * @param numCompiles The number of chunks. 310 * @param sourcesPerCompile The number of sources per chunk. 311 * @return 312 */ 313 CompileChunk[] createCompileChunks(Map<String,Set<URI>> pkgSrcs, 314 Map<String,Set<String>> oldPackageDependents, 315 int numCompiles, 316 int sourcesPerCompile) { 317 318 CompileChunk[] compileChunks = new CompileChunk[numCompiles]; 319 for (int i=0; i<compileChunks.length; ++i) { 320 compileChunks[i] = new CompileChunk(); 321 } 322 323 // Now go through the packages and spread out the source on the different chunks. 324 int ci = 0; 325 // Sort the packages 326 String[] packageNames = pkgSrcs.keySet().toArray(new String[0]); 327 Arrays.sort(packageNames); 328 String from = null; 329 for (String pkgName : packageNames) { 330 CompileChunk cc = compileChunks[ci]; 331 Set<URI> s = pkgSrcs.get(pkgName); 332 if (cc.srcs.size()+s.size() > sourcesPerCompile && ci < numCompiles-1) { 333 from = null; 334 ci++; 335 cc = compileChunks[ci]; 336 } 337 cc.numPackages++; 338 cc.srcs.addAll(s); 339 340 // Calculate nice package names to use as information when compiling. 341 String justPkgName = Util.justPackageName(pkgName); 342 // Fetch how many packages depend on this package from the old build state. 343 Set<String> ss = oldPackageDependents.get(pkgName); 344 if (ss != null) { 345 // Accumulate this information onto this chunk. 346 cc.numDependents += ss.size(); 347 } 348 if (from == null || from.trim().equals("")) from = justPkgName; 349 cc.pkgNames.append(justPkgName+"("+s.size()+") "); 350 cc.pkgFromTos = from+" to "+justPkgName; 351 } 352 // If we are compiling serially, sort the chunks, so that the chunk (with the most dependents) (usually the chunk 353 // containing java.lang.Object, is to be compiled first! 354 // For concurrent compilation, this does not matter. 355 Arrays.sort(compileChunks); 356 return compileChunks; 357 } 358} 359