src/share/classes/com/sun/tools/sjavac/CompileJavaPackages.java

Tue, 24 Dec 2013 09:17:37 -0800

author
ksrini
date
Tue, 24 Dec 2013 09:17:37 -0800
changeset 2227
998b10c43157
parent 1861
dcc6a52bf363
child 2525
2eb010b6cb22
permissions
-rw-r--r--

8029230: Update copyright year to match last edit in jdk8 langtools repository for 2013
Reviewed-by: ksrini
Contributed-by: steve.sides@oracle.com

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

mercurial