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