现在的位置: 首页 > 综合 > 正文

How to distinguish between 32 and 64-bit JVM

2018年03月18日 ⁄ 综合 ⁄ 共 1987字 ⁄ 字号 评论关闭


There's no public API that allows you to distinguish between 32 and 64-bit operation.  Think of 64-bit as just another platform in the write once, run anywhere tradition.  However, if you'd like to write
code which is platform specific (shame on you),  the system property sun.arch.data.model has the value "32", "64", or "unknown".  

the System Property sun.arch.data.model
String dataModel = System.getProperty("sun.arch.data.model");
if("32").equals(dataModel){
    // load 32-bit DLL
}else if("64").equals(dataModel){
    // load 64-bit DLL
}else{
    // error handling
}

We can also use System.getProperty("os.arch")
if ("x86".equals(System.getProperty("os.arch"))) {
   // 32 bit
} else if ("x64".equals(System.getProperty("os.arch"))) {
   // 64 bit
}

 But either System.getProperty("sun.arch.data.model") or System.getProperty("os.arch") can get if the jvm (not the host) is 32 or 64-bit.

Getting the jvm which is 32 or 64-bit information is usefull in some scenarios. For example, you would like to set the chunk size depending on whether jvm is 32 or 64-bit.
Here is a sample in Lucene FSDirectory class which set default chunk size.

public abstract class FSDirectory extends Directory {

  /**
   * Default read chunk size.  This is a conditional default: on 32bit JVMs, it defaults to 100 MB.  On 64bit JVMs, it's
   * <code>Integer.MAX_VALUE</code>.
   *
   * @see #setReadChunkSize
   */
  public static final int DEFAULT_READ_CHUNK_SIZE = Constants.JRE_IS_64BIT ? Integer.MAX_VALUE : 100 * 1024 * 1024;

Constants.JRE_IS_64BIT code is following:

 /** True iff running on a 64bit JVM */
  public static final boolean JRE_IS_64BIT;
  
  static {
    boolean is64Bit = false;
    try {
      final Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
      final Field unsafeField = unsafeClass.getDeclaredField("theUnsafe");
      unsafeField.setAccessible(true);
      final Object unsafe = unsafeField.get(null);
      final int addressSize = ((Number) unsafeClass.getMethod("addressSize")
        .invoke(unsafe)).intValue();
      //System.out.println("Address size: " + addressSize);
      is64Bit = addressSize >= 8;
    } catch (Exception e) {
      final String x = System.getProperty("sun.arch.data.model");
      if (x != null) {
        is64Bit = x.indexOf("64") != -1;
      } else {
        if (OS_ARCH != null && OS_ARCH.indexOf("64") != -1) {
          is64Bit = true;
        } else {
          is64Bit = false;
        }
      }
    }
    JRE_IS_64BIT = is64Bit;

抱歉!评论已关闭.