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

Mon, 11 Mar 2013 19:03:35 -0700

author
ohrstrom
date
Mon, 11 Mar 2013 19:03:35 -0700
changeset 1625
fbb6e470079d
parent 1504
22e417cdddee
child 1861
dcc6a52bf363
permissions
-rw-r--r--

8009843: sjavac should accept -cp as synonym for -classpath
Reviewed-by: jjg

     1 /*
     2  * Copyright (c) 2012, 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         if (osarch.equals("i386")) {
   140             // For 32 bit platforms, assume it is slightly smaller
   141             // because of smaller object headers and pointers.
   142             kbPerFile = 119;
   143         }
   144         int numRequiredMBytes = (kbPerFile*numSources)/1024;
   145         Log.debug("For os.arch "+osarch+" the empirically determined heap required per file is "+kbPerFile+"KiB");
   146         Log.debug("Server has "+numMBytes+"MiB of heap.");
   147         Log.debug("Heuristics say that we need "+numRequiredMBytes+"MiB of heap for all source files.");
   148         // Perform heuristics to see how many cores we can use,
   149         // or if we have to the work serially in smaller chunks.
   150         if (numMBytes < numRequiredMBytes) {
   151             // Ouch, cannot fit even a single compile into the heap.
   152             // Split it up into several serial chunks.
   153             concurrentCompiles = false;
   154             // Limit the number of sources for each compile to 500.
   155             if (numSources < 500) {
   156                 numCompiles = 1;
   157                 sourcesPerCompile = numSources;
   158                 Log.debug("Compiling as a single source code chunk to stay within heap size limitations!");
   159             } else if (sourcesPerCompile > 500) {
   160                 // This number is very low, and tuned to dealing with the OpenJDK
   161                 // where the source is >very< circular! In normal application,
   162                 // with less circularity the number could perhaps be increased.
   163                 numCompiles = numSources / 500;
   164                 sourcesPerCompile = numSources/numCompiles;
   165                 Log.debug("Compiling source as "+numCompiles+" code chunks serially to stay within heap size limitations!");
   166             }
   167         } else {
   168             if (numCompiles > 1) {
   169                 // Ok, we can fit at least one full compilation on the heap.
   170                 float usagePerCompile = (float)numRequiredMBytes / ((float)numCompiles * (float)0.7);
   171                 int usage = (int)(usagePerCompile * (float)numCompiles);
   172                 Log.debug("Heuristics say that for "+numCompiles+" concurrent compiles we need "+usage+"MiB");
   173                 if (usage > numMBytes) {
   174                     // Ouch it does not fit. Reduce to a single chunk.
   175                     numCompiles = 1;
   176                     sourcesPerCompile = numSources;
   177                     // What if the relationship betweem number of compile_chunks and num_required_mbytes
   178                     // is not linear? Then perhaps 2 chunks would fit where 3 does not. Well, this is
   179                     // something to experiment upon in the future.
   180                     Log.debug("Limiting compile to a single thread to stay within heap size limitations!");
   181                 }
   182             }
   183         }
   185         Log.debug("Compiling sources in "+numCompiles+" chunk(s)");
   187         // Create the chunks to be compiled.
   188         final CompileChunk[] compileChunks = createCompileChunks(pkgSrcs, oldPackageDependents,
   189                 numCompiles, sourcesPerCompile);
   191         if (Log.isDebugging()) {
   192             int cn = 1;
   193             for (CompileChunk cc : compileChunks) {
   194                 Log.debug("Chunk "+cn+" for "+id+" ---------------");
   195                 cn++;
   196                 for (URI u : cc.srcs) {
   197                     Log.debug(""+u);
   198                 }
   199             }
   200         }
   202         // The return values for each chunked compile.
   203         final int[] rn = new int[numCompiles];
   204         // The requets, might or might not run as a background thread.
   205         final Thread[] requests  = new Thread[numCompiles];
   207         final Set<URI>             fvisible_sources = visibleSources;
   208         final Map<URI,Set<String>> fvisible_classes = visibleClasses;
   210         long start = System.currentTimeMillis();
   212         for (int i=0; i<numCompiles; ++i) {
   213             final int ii = i;
   214             final CompileChunk cc = compileChunks[i];
   216             // Pass the num_cores and the id (appended with the chunk number) to the server.
   217             final String cleanedServerSettings = psServerSettings+",poolsize="+numCores+",id="+id+"-"+ii;
   218             final PrintStream fout = out;
   219             final PrintStream ferr = err;
   221             requests[ii] = new Thread() {
   222                 @Override
   223                 public void run() {
   224                                         rn[ii] = JavacServer.useServer(cleanedServerSettings,
   225                                                            Main.removeWrapperArgs(args),
   226                                                                cc.srcs,
   227                                                            fvisible_sources,
   228                                                            fvisible_classes,
   229                                                            packageArtifacts,
   230                                                            packageDependencies,
   231                                                            packagePubapis,
   232                                                            null,
   233                                                            fout, ferr);
   234                 }
   235             };
   237             if (cc.srcs.size() > 0) {
   238                 String numdeps = "";
   239                 if (cc.numDependents > 0) numdeps = "(with "+cc.numDependents+" dependents) ";
   240                 if (!incremental || cc.numPackages > 16) {
   241                     String info = "("+cc.pkgFromTos+")";
   242                     if (info.equals("( to )")) {
   243                         info = "";
   244                     }
   245                     Log.info("Compiling "+cc.srcs.size()+" files "+numdeps+"in "+cc.numPackages+" packages "+info);
   246                 } else {
   247                     Log.info("Compiling "+cc.pkgNames+numdeps);
   248                 }
   249                 if (concurrentCompiles) {
   250                     requests[ii].start();
   251                 }
   252                 else {
   253                     requests[ii].run();
   254                     // If there was an error, then stop early when running single threaded.
   255                     if (rn[i] != 0) {
   256                         return false;
   257                     }
   258                 }
   259             }
   260         }
   261         if (concurrentCompiles) {
   262             // If there are background threads for the concurrent compiles, then join them.
   263             for (int i=0; i<numCompiles; ++i) {
   264                 try { requests[i].join(); } catch (InterruptedException e) { }
   265             }
   266         }
   268         // Check the return values.
   269         for (int i=0; i<numCompiles; ++i) {
   270             if (compileChunks[i].srcs.size() > 0) {
   271                 if (rn[i] != 0) {
   272                     rc = false;
   273                 }
   274             }
   275         }
   276         long duration = System.currentTimeMillis() - start;
   277         long minutes = duration/60000;
   278         long seconds = (duration-minutes*60000)/1000;
   279         Log.debug("Compilation of "+numSources+" source files took "+minutes+"m "+seconds+"s");
   281         return rc;
   282     }
   285     /**
   286      * Split up the sources into compile chunks. If old package dependents information
   287      * is available, sort the order of the chunks into the most dependent first!
   288      * (Typically that chunk contains the java.lang package.) In the future
   289      * we could perhaps improve the heuristics to put the sources into even more sensible chunks.
   290      * Now the package are simple sorted in alphabetical order and chunked, then the chunks
   291      * are sorted on how dependent they are.
   292      *
   293      * @param pkgSrcs The sources to compile.
   294      * @param oldPackageDependents Old package dependents, if non-empty, used to sort the chunks.
   295      * @param numCompiles The number of chunks.
   296      * @param sourcesPerCompile The number of sources per chunk.
   297      * @return
   298      */
   299     CompileChunk[] createCompileChunks(Map<String,Set<URI>> pkgSrcs,
   300                                  Map<String,Set<String>> oldPackageDependents,
   301                                  int numCompiles,
   302                                  int sourcesPerCompile) {
   304         CompileChunk[] compileChunks = new CompileChunk[numCompiles];
   305         for (int i=0; i<compileChunks.length; ++i) {
   306             compileChunks[i] = new CompileChunk();
   307         }
   309         // Now go through the packages and spread out the source on the different chunks.
   310         int ci = 0;
   311         // Sort the packages
   312         String[] packageNames = pkgSrcs.keySet().toArray(new String[0]);
   313         Arrays.sort(packageNames);
   314         String from = null;
   315         for (String pkgName : packageNames) {
   316             CompileChunk cc = compileChunks[ci];
   317             Set<URI> s = pkgSrcs.get(pkgName);
   318             if (cc.srcs.size()+s.size() > sourcesPerCompile && ci < numCompiles-1) {
   319                 from = null;
   320                 ci++;
   321                 cc = compileChunks[ci];
   322             }
   323             cc.numPackages++;
   324             cc.srcs.addAll(s);
   326             // Calculate nice package names to use as information when compiling.
   327             String justPkgName = Util.justPackageName(pkgName);
   328             // Fetch how many packages depend on this package from the old build state.
   329             Set<String> ss = oldPackageDependents.get(pkgName);
   330             if (ss != null) {
   331                 // Accumulate this information onto this chunk.
   332                 cc.numDependents += ss.size();
   333             }
   334             if (from == null || from.trim().equals("")) from = justPkgName;
   335             cc.pkgNames.append(justPkgName+"("+s.size()+") ");
   336             cc.pkgFromTos = from+" to "+justPkgName;
   337         }
   338         // If we are compiling serially, sort the chunks, so that the chunk (with the most dependents) (usually the chunk
   339         // containing java.lang.Object, is to be compiled first!
   340         // For concurrent compilation, this does not matter.
   341         Arrays.sort(compileChunks);
   342         return compileChunks;
   343     }
   344 }

mercurial