Java arrays contiguous in memory?

are java arrays always contiguous in memory? or how does java save his arrays?
i need to know because i wrote an algorithm with a lot of array length changing, and i wonder if it consumes a lot or not, maybe java uses virtual memory arrays like those here :
http://developers.sun.com/solaris/articles/virtual_memory_arrays.html
any answer is welcome,
Nck.

The internal layout of objects (including arrays) is explicitly undefined by the JVM standard:
http://java.sun.com/docs/books/vmspec/2nd-edition/html/Overview.doc.html#16066
So you can't assume that arrays are implemented in any particular way on any given JVM. But the Get<Type>ArrayElements JNI functions can give you a clue about it for the current JVM.
But I don't really understand the background of the question. What do you mean by "a lot of array length changing"? Java arrays can't be resized, whether from bytecode or JNI.
-slj-

Similar Messages

  • Any way to Initialize Java Array to start with 1

    Hi Friends,
    Is there anyway to initialize the java array with starting with 1 instead of normal 0.
    Thanks and Regards.
    JG

    JamesGeorge wrote:
    Hi Jacob,
    Thanks for you time..
    Coding like 1 - n will make everything uneasy, I find in other languages like vbscript,lotusscript it can be done..so just a thought to check in Java too..
    Is there any valid reason for Java/Sun guys to start the arrays,vectors and other collections with 0
    Thanks
    JJShort answer: Java is a C-based language, and C arrays are zero-based so the rest are also zero-based for consistency.
    Long answer: Arrays are implemented as contiguous areas of memory starting from a certain memory address, and loading from a zero-based array implies one less CPU instruction than loading from a one-based array.
    Zero-based:
    - LOAD A, ArrayAddress
    - LOAD B, Index
    - MUL B, ElementSize
    - ADD A, B
    - LOAD (A)
    One-based:
    - LOAD A, ArrayAddress
    - LOAD B, Index
    - ADD B, -1
    - MUL B, ElementSize
    - ADD A, B
    - LOAD (A)

  • [JNI Beginner] GC of Java arrays returned by the native code

    Hello all,
    I am beginning with JNI, to integrate a C library that pilots an industrial equipment, into a java UI. This library enables to exchange various proprietary PDUs (protocol data units), with the equipment, up and down (request/replies). Both requests and replies are arrays of bytes (+char*+).
    "Request" byte arrays are constructed by Java code, which passes them to the JNI code that glues with the lib. "Reply" byte arrays are returned to the Java code, which analyzes them.
    The "return reply" part is very similar to this [tutorial example|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html] , which returns bytes read from a file. However there's something I don't understand with regard to garbage collection of the returned byte array:
    - in this stock example, the C code creates a Java byte array fills it, and simply returns it (example code stripped to highlight only the parts relevant to my question):
        jByteArray=(*env)->NewByteArray(env, size);
        (*env)->SetByteArrayRegion(env, jByteArray, 0, size, (jbyte *)sourceBytes);
        return (jByteArray);What will happen to this Java array (jByteArray) with regard to garbage collection?
    - if it's no more referenced (the example Java code just systemouts it and forgets it), will it be eligible to GC?
    - if it is referenced by a Java variable (in my case, I plan to keep a reference to several replies as the business logic requires to analyze several of them together), do regular Java language GC rules apply, and prevent eligibility of the array to GC as long as it's referenced?
    That may sound obvious, but what mixes me up is that the same tutorial describes memory issues in subsequent chapters: spécifically, the section on "passing arrays states that:
    [in the example] the array is returned to the calling Java language method, which in turn, garbage collects the reference to the array when it is no longer usedThis seems to answer "yes" to both my questions above :o) But it goes on:
    The array can be explicitly freed with the following call:
    {code} (*env)-> ReleaseByteArrayElements(env, jByteArray, (jbyte *)sourceBytes, 0);{code}Under what circumstances would one need to explicitly free jByteArray when it's about to be returned to the Java calling method? Or does this sentence apply to completely different situations (such as, when the array is +not+ returned as is to a Java method)?
    The tutorial's next section has a much-expected +memory issues+ paragraph, from which I quote:
    By default, JNI uses local references when creating objects inside a native method. This means when the method returns, the references are eligible to be garbage collected.I assume this means, +unless the references are assigned, in the Java code, to a Java variable+, right?
    If you want an object to persist across native method calls, use a global reference instead. A global reference is created from a local reference by calling NewGlobalReference on the the local reference.I assume this enables the C code to maintain a global reference to a java object even if it's not referenced anymore from the Java variables, right?
    I also checked the [JNI specification|http://download-llnw.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp1242] , but this didn't clear the doubt completely:
    *Global and Local References*
    The JNI divides object references used by the native code into two categories: local and global references. Local references are valid for the duration of a native method call, and are automatically freed after the native method returns. Global references remain valid until they are explicitly freed.
    Objects are passed to native methods as local references. All Java objects returned by JNI functions are local references. The JNI allows the programmer to create global references from local references. JNI functions that expect Java objects accept both global and local references. A native method may return a local or global reference to the VM as its resultAgain I assume the intent is that Global references are meant for objects that have to survive across native calls, regardless of whether they are referenced by Java code. But what worries me is that combining both sentences end up in +All Java objects returned by JNI functions are local references (...) and are automatically freed after the native method returns.+.
    Could you clarify how to make sure that my Java byte arrays, be they allocated in C code, behave consistently with a Java array allocated in Java code (I'm familiar already with GC of "regular" Java objects)?
    Thanks in advance, and best regards,
    J.

    jduprez wrote:
    Hello all,
    I am beginning with JNI, to integrate a C library that pilots an industrial equipment, into a java UI. This library enables to exchange various proprietary PDUs (protocol data units), with the equipment, up and down (request/replies). Both requests and replies are arrays of bytes (+char*+).
    "Request" byte arrays are constructed by Java code, which passes them to the JNI code that glues with the lib. "Reply" byte arrays are returned to the Java code, which analyzes them.
    The "return reply" part is very similar to this [tutorial example|http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jniexamp.html] , which returns bytes read from a file. However there's something I don't understand with regard to garbage collection of the returned byte array:
    - in this stock example, the C code creates a Java byte array fills it, and simply returns it (example code stripped to highlight only the parts relevant to my question):
        jByteArray=(*env)->NewByteArray(env, size);
    (*env)->SetByteArrayRegion(env, jByteArray, 0, size, (jbyte *)sourceBytes);
    return (jByteArray);What will happen to this Java array (jByteArray) with regard to garbage collection?It will be collected when it is no longer referenced.
    The fact that you created it in jni doesn't change that.
    The array can be explicitly freed with the following call:
    (*env)-> ReleaseByteArrayElements(env, jByteArray, (jbyte *)sourceBytes, 0);Under what circumstances would one need to explicitly free jByteArray when it's about to be returned to the Java calling method? Or does this sentence apply to completely different situations (such as, when the array is not returned as is to a Java method)?
    Per what the tutorial says it is either poorly worded or just wrong.
    An array which has been properly initialized it a just a java object. Thus it can be freed like any other object.
    Per your original question that does not concern you because you return it.
    In terms of why you need to explicitly free local references.
    [http://download-llnw.oracle.com/javase/6/docs/technotes/guides/jni/spec/design.html#wp16785]
    The tutorial's next section has a much-expected memory issues paragraph, from which I quote:
    By default, JNI uses local references when creating objects inside a native method. This means when the method returns, the references are eligible to be garbage collected.I assume this means, unless the references are assigned, in the Java code, to a Java variable, right?As stated it is not precise.
    The created objects are tracked by the VM. When they are eligible to be collected they are.
    If you create a local reference and do NOTHING that creates an active reference elsewhere then when the executing thread returns to the VM then the local references are eligible to be collected.
    >
    If you want an object to persist across native method calls, use a global reference instead. A global reference is created from a local reference by calling NewGlobalReference on the the local reference.That is not precise. The scope is the executing thread. You can pass a local reference to another method without problem.
    I assume this enables the C code to maintain a global reference to a java object even if it's not referenced anymore from the Java variables, right?
    It enables access to it to be insured across multiple threads in terms of execution scope. Normally you should not use them.

  • JAVA Array sizes - how to expand + See nice example code

    Hi, We are returning tables of VARCHAR, NUMBERS, BOOLEANs and
    the like to Java using PL2JAVA and Oracle Sessions. Problem I am
    having is the size of the Array's are undetermined, but it
    appears these must be set before calling package - if package
    returns more rows in tables than the calling Java arrays have,
    then it fails. If we assign too many then I guess we are using
    memory which will be wasted - important when this system could
    have 100 simultaneous users/connections.
    Has anyone got any advice - people may find the sample code below
    useful at worse.
    PACKAGE INTERFACE:
    FUNCTION ssfk_get_metadata.ssfp_get_2metadata RETURNS VARCHAR2
    Argument Name Type In/Out
    Default?
    P_USER_PERSON_ID NUMBER(10) IN
    P_SELF_SERVE_APPLICATION VARCHAR2 IN
    PT_DATA_SOURCE TABLE OF VARCHAR2(60) OUT
    PT_PROMPT TABLE OF VARCHAR2(30) OUT
    PT_DATA_TYPE TABLE OF VARCHAR2(30) OUT
    PT_DATA_LENGTH TABLE OF NUMBER OUT
    PT_DECIMAL_PLACES TABLE OF NUMBER OUT
    PT_MANDATORY_IND TABLE OF VARCHAR2(1) OUT
    PT_UCASE_IND TABLE OF VARCHAR2(1) OUT
    PT_DISPLAY_ONLY_IND TABLE OF VARCHAR2(1) OUT
    PT_WEB_LINK_CD TABLE OF VARCHAR2(10) OUT
    P_TABLE_INDEX BINARY_INTEGER OUT
    P_MESSAGE_NUM NUMBER(5) OUT
    Code example:
    public static String getApplicationMetaData (String
    strPersonID, String strApplication, Session sesSession)
    String strClientString = "";
    if (sesSession==null)
    return "CONNECTION ERROR";
    else
    Double dblUser = new Double(strPersonID);
    //initialising of IN parameters
    PDouble pdbUserPersonId = new PDouble
    (dblUser.intValue());
    PStringBuffer pstSelfServeApplication = new
    PStringBuffer (strApplication);
    //initialising of OUT parameters
    PStringBuffer pstDataSource[] = new PStringBuffer
    [intArraySize];
    PStringBuffer pstPrompt[] = new PStringBuffer
    [intArraySize];
    PStringBuffer pstDataType[] = new PStringBuffer
    [intArraySize];
    PDouble pdbDataLength[] = new PDouble [intArraySize];
    PDouble pdbDecimalPlaces[] = new PDouble
    [intArraySize];
    PStringBuffer pstMandatoryIND[] = new PStringBuffer
    [intArraySize];
    PStringBuffer pstUCaseIND[] = new PStringBuffer
    [intArraySize];
    PStringBuffer pstDisplayOnlyIND[] = new PStringBuffer
    [intArraySize];
    PStringBuffer pstWebLinkCode[] = new PStringBuffer
    [intArraySize];
    PInteger pinTableIndex = new PInteger (0);
    PDouble pdbMessageNum = new PDouble (0);
    //initialising of RETURN parameters
    PStringBuffer pstReturn = new PStringBuffer("N");
    //setting the array items sizes
    for (int i=0; i<pstDataSource.length; i++)
    pstDataSource[i] = new PStringBuffer(60);
    pstPrompt[i] = new PStringBuffer(30);
    pstDataType[i] = new PStringBuffer(30);
    pdbDataLength[i] = new PDouble(-1);
    pdbDecimalPlaces[i] = new PDouble(-1);
    pstMandatoryIND[i] = new PStringBuffer(1);
    pstUCaseIND[i] = new PStringBuffer(1);
    pstDisplayOnlyIND[i] = new PStringBuffer(1);
    pstWebLinkCode[i] = new PStringBuffer(10);
    try
    strClientString = strClientString.concat ("001");
    ssfk_get_metadata ssfAppMetaData = new
    ssfk_get_metadata (sesSession);
    strClientString = strClientString.concat ("002");
    pstReturn = ssfAppMetaData.ssfp_get_2metadata
    (pdbUserPersonId, pstSelfServeApplication, pstDataSource,
    pstPrompt, pstDataType, pdbDataLength, pdbDecimalPlaces,
    pstMandatoryIND, pstUCaseIND, pstDisplayOnlyIND, pstWebLinkCode,
    pinTableIndex, pdbMessageNum);
    strClientString = strClientString.concat ("003");
    if
    (pstReturn.stringValue().equalsIgnoreCase("Y"))
    strClientString = strClientString.concat
    ("WORKED");
    return strClientString;
    else
    return "ERROR";
    catch (Exception e)
    return strClientString + "ERROR:" + e.getMessage
    Thanks for any assistance.
    null

    Play with Java Vectors. They are automatic expanding arrays!
    Just add elements and get them later. One thing that's tricky
    is that Vectors only store and return elements as Objects so you
    have to explicitly recast them.
    -dan
    Richard Leigh (guest) wrote:
    : Hi, We are returning tables of VARCHAR, NUMBERS, BOOLEANs and
    : the like to Java using PL2JAVA and Oracle Sessions. Problem I
    am
    : having is the size of the Array's are undetermined, but it
    : appears these must be set before calling package - if package
    : returns more rows in tables than the calling Java arrays have,
    : then it fails. If we assign too many then I guess we are
    using
    : memory which will be wasted - important when this system could
    : have 100 simultaneous users/connections.
    : Has anyone got any advice - people may find the sample code
    below
    : useful at worse.
    : PACKAGE INTERFACE:
    : FUNCTION ssfk_get_metadata.ssfp_get_2metadata RETURNS VARCHAR2
    : Argument Name Type In/Out
    : Default?
    : P_USER_PERSON_ID NUMBER(10) IN
    : P_SELF_SERVE_APPLICATION VARCHAR2 IN
    : PT_DATA_SOURCE TABLE OF VARCHAR2(60) OUT
    : PT_PROMPT TABLE OF VARCHAR2(30) OUT
    : PT_DATA_TYPE TABLE OF VARCHAR2(30) OUT
    : PT_DATA_LENGTH TABLE OF NUMBER OUT
    : PT_DECIMAL_PLACES TABLE OF NUMBER OUT
    : PT_MANDATORY_IND TABLE OF VARCHAR2(1) OUT
    : PT_UCASE_IND TABLE OF VARCHAR2(1) OUT
    : PT_DISPLAY_ONLY_IND TABLE OF VARCHAR2(1) OUT
    : PT_WEB_LINK_CD TABLE OF VARCHAR2(10) OUT
    : P_TABLE_INDEX BINARY_INTEGER OUT
    : P_MESSAGE_NUM NUMBER(5) OUT
    : Code example:
    : public static String getApplicationMetaData (String
    : strPersonID, String strApplication, Session sesSession)
    : String strClientString = "";
    : if (sesSession==null)
    : return "CONNECTION ERROR";
    : else
    : Double dblUser = new Double(strPersonID);
    : //initialising of IN parameters
    : PDouble pdbUserPersonId = new PDouble
    : (dblUser.intValue());
    : PStringBuffer pstSelfServeApplication = new
    : PStringBuffer (strApplication);
    : //initialising of OUT parameters
    : PStringBuffer pstDataSource[] = new PStringBuffer
    : [intArraySize];
    : PStringBuffer pstPrompt[] = new PStringBuffer
    : [intArraySize];
    : PStringBuffer pstDataType[] = new PStringBuffer
    : [intArraySize];
    : PDouble pdbDataLength[] = new PDouble
    [intArraySize];
    : PDouble pdbDecimalPlaces[] = new PDouble
    : [intArraySize];
    : PStringBuffer pstMandatoryIND[] = new
    PStringBuffer
    : [intArraySize];
    : PStringBuffer pstUCaseIND[] = new PStringBuffer
    : [intArraySize];
    : PStringBuffer pstDisplayOnlyIND[] = new
    PStringBuffer
    : [intArraySize];
    : PStringBuffer pstWebLinkCode[] = new PStringBuffer
    : [intArraySize];
    : PInteger pinTableIndex = new PInteger (0);
    : PDouble pdbMessageNum = new PDouble (0);
    : //initialising of RETURN parameters
    : PStringBuffer pstReturn = new PStringBuffer("N");
    : //setting the array items sizes
    : for (int i=0; i<pstDataSource.length; i++)
    : pstDataSource[i] = new PStringBuffer(60);
    : pstPrompt[i] = new PStringBuffer(30);
    : pstDataType[i] = new PStringBuffer(30);
    : pdbDataLength[i] = new PDouble(-1);
    : pdbDecimalPlaces[i] = new PDouble(-1);
    : pstMandatoryIND[i] = new PStringBuffer(1);
    : pstUCaseIND[i] = new PStringBuffer(1);
    : pstDisplayOnlyIND[i] = new PStringBuffer(1);
    : pstWebLinkCode[i] = new PStringBuffer(10);
    : try
    : strClientString = strClientString.concat
    ("001");
    : ssfk_get_metadata ssfAppMetaData = new
    : ssfk_get_metadata (sesSession);
    : strClientString = strClientString.concat
    ("002");
    : pstReturn = ssfAppMetaData.ssfp_get_2metadata
    : (pdbUserPersonId, pstSelfServeApplication, pstDataSource,
    : pstPrompt, pstDataType, pdbDataLength, pdbDecimalPlaces,
    : pstMandatoryIND, pstUCaseIND, pstDisplayOnlyIND,
    pstWebLinkCode,
    : pinTableIndex, pdbMessageNum);
    : strClientString = strClientString.concat
    ("003");
    : if
    : (pstReturn.stringValue().equalsIgnoreCase("Y"))
    : strClientString = strClientString.concat
    : ("WORKED");
    : return strClientString;
    : else
    : return "ERROR";
    : catch (Exception e)
    : return strClientString + "ERROR:" +
    e.getMessage
    : Thanks for any assistance.
    null

  • Problems creating a Java Array using JNI-HELP!

    Hi,
    I am trying to create a Java Array using JNI.I have posted the code below. The problem is that the oth element is added correctly to the Array but when the JVM gets to the next element...it goes for a toss. It is not able to create a new instance of the object in GetUGEntity() function...there seems to be some problem in creating a new instance of the object!
    Can somebody help me with this?
    jobject GetUGEntity(JNIEnv *env, UF_DISP_j3d_entity_t* entity_list)
         int numVerts=0, numStrips=0;
         jfieldID fid;
         jdoubleArray jTransform=NULL;
         jstring jstrName=NULL;
         jdoubleArray jNormals=NULL;
         //Init an Entity object
         cout<< "**Getting New Class Reference...";
         jclass jEntity = env->FindClass("Lcom/wipro/java3d/rmi/Entity;");
         cout << "**got Class reference..."<<endl;
         if (jEntity == NULL)
              return NULL;
         cout<<"Creating new object instance...";
         jmethodID mIDInit = env->GetMethodID(jEntity, "<init>", "()V");
         cout<<"Got java method id...";
         jobject javaObj = env->NewObject(jEntity, mIDInit);
         if (javaObj==NULL)
              return NULL;
         cout << "Created!" << endl;
         //Entity ID
         cout<< "**Setting eid...";
         fid=env->GetFieldID(jEntity,"eid","I");
         jint eid = (jint)(entity_list)->eid;
         env->SetIntField(javaObj, fid, eid);
         //env->DeleteLocalRef(eid);
         cout << "Done!" << endl;
         cout << "Done!" << endl;
         cout<< "**Returning jobject...";
         return javaObj;
    jobjectArray createJArray(JNIEnv* env, UF_DISP_j3d_entity_t** entity_list, int noOfEntities )
         UF_DISP_j3d_entity_t* tempVar=NULL;
         cout<<"*Creating Jobjectarray...";
         jobjectArray jEntityArray = (jobjectArray) env->NewObjectArray(noOfEntities,
              env->FindClass("Lcom/wipro/java3d/rmi/Entity;"),NULL);
         cout<<"Created!"<<endl;
         for(int i=0; i<noOfEntities;++i)
              tempVar = &(*entity_list);
              if (tempVar !=NULL)
                   cout<<"*Trying to get Entity...."<<endl;
                   jobject jEntity = GetUGEntity(env, tempVar);
                   if (jEntity!= NULL)
                        cout<<"Got Entity!" <<endl;
                        cout <<"*Setting Array Element....";
                        env->SetObjectArrayElement(jEntityArray, i, jEntity);
                        cout << "Done!" << endl;
                   else
                        printf("ERROR: Did not get Entity Reference");
              else
                   printf("ERROR: Got a NULL Reference!");
         return jEntityArray;

    Hi Deepak,
    Could you please let us know upto which line your code is going safe. Try printing the value in the structure before you send that to the method GetUGEntity().
    I am not too sure that would be a problem. But I have faced a problem like this, wherein I tried to access a structure for which I have not allocated memory and hence got exception because of that.
    Since your JNI code seems to be error free, I got doubt on your C part. Sorry.
    Dhamo.

  • Array as Shared Memory - performance bottleneck

    Array as shared memory - performance bottleneck
    Hello,
    currently I work on a multi-threaded application, where many threads work on shared memory.
    I wondering why the application doesn't become faster by using many threads (I have i7 machine).
    Here is an example for initialization in single thread:
              final int arrayLength = (int)1e7;
              final int threadNumber = Runtime.getRuntime().availableProcessors();
              long startTime;
               * init array in single thread
              Integer[] a1 = new Integer[arrayLength];
              startTime = System.currentTimeMillis();
              for(int i=0; i<arrayLength; i++){
                   a1[i] = i;
              System.out.println("single thread=" + (System.currentTimeMillis()-startTime));and here initialization with many threads:
               * init array in many threads
              final Integer[] a3 = new Integer[arrayLength];
              List<Thread> threadList = new ArrayList<Thread>();
              for(int i=0; i<threadNumber; i++){
                   final int iF = i;
                   Thread t = new Thread(new Runnable(){
                        @Override
                        public void run() {
                             int end = (iF+1)*offset;
                             if(iF==(threadNumber-1))
                                  end = a3.length;
                             for(int i=iF*offset; i<end; i++){
                                  a3[i] = i;
                   threadList.add(t);
              startTime = System.currentTimeMillis();
              for(Thread t:threadList)
                   t.start();
              for(Thread t:threadList)
                   t.join();After execution it looks like this:
    single thread=2372
    many threads List=3760I have i7 4GB RAM
    System + Parameters:
    JVM-64bit JDK1.6.0_14
    -Xmx3g
    Why the executing of one thread is faster as executing of many threads?
    As you can see I didn't use any synchronization.
    Maybe I have to configure JVM in some way to gain wished performance (I expected the performance gain on i7 x8 times) ?

    Hello,
    I'm from [happy-guys|http://www.happy-guys.com] , and we developed new sorting-algorithm to sort an array on the multi-core machine.
    But after the algorithm was implemented it was a little-bit slower as standard sorting-algorithm from JDK (Array.sort(...)). After searching for the reason, I created performance tests which shows that the arrays in Java don't allow to access them by many threads at the same time.
    The bad news is: different threads slowdown each-other even if they use different array-objects.
    I believe all array-objects are natively managed by a global manager in JVM, thus this manager builds a global-lock for all threads.
    Only one thread can access any array at the same time!
    I used:
    Software:
    1)Windows Vista 64bit,
    2) java version "1.6.0_14"
    Java(TM) SE Runtime Environment (build 1.6.0_14-b08)
    Java HotSpot(TM) 64-Bit Server VM (build 14.0-b16, mixed mode)
    Hardware:
    Intel(R) Core(TM) i7 CPU 920 @ 2,67GHz 2,79 GHz, 6G RAM
    Test1: initialization of array in a single thread
    Test2: the array initialization in many threads on the single array
    Test3: array initialization in many threads on many arrays
    Results in ms:
    Test1 = 5588
    Test2 = 4976
    Test3 = 5429
    Test1:
    package org.happy.concurrent.sort.forum;
    * simulates the initialization of array in a single thread
    * @author Andreas Hollmann
    public class ArraySingleThread {
         public static void main(String[] args) throws InterruptedException {
              final int arrayLength = (int)2e7;
              long startTime;
                    * init array in single thread
                   Integer[] a1 = new Integer[arrayLength];
                   startTime = System.currentTimeMillis();
                   for(int i=0; i<arrayLength; i++){
                        a1[i] = i;
                   System.out.println("single thread=" + (System.currentTimeMillis()-startTime));
    }Test2:
    package org.happy.concurrent.sort.forum;
    import java.util.ArrayList;
    import java.util.List;
    * simulates the array initialization in many threads on the single array
    * @author Andreas Hollmann
    public class ArrayManyThreads {
         public static void main(String[] args) throws InterruptedException {
              final int arrayLength = (int)2e7;
              final int threadNumber = Runtime.getRuntime().availableProcessors();
              long startTime;
              final int offset = arrayLength/threadNumber;
                    * init array in many threads
                   final Integer[] a = new Integer[arrayLength];
                   List<Thread> threadList = new ArrayList<Thread>();
                   for(int i=0; i<threadNumber; i++){
                        final int iF = i;
                        Thread t = new Thread(new Runnable(){
                             @Override
                             public void run() {
                                  int end = (iF+1)*offset;
                                  if(iF==(threadNumber-1))
                                       end = a.length;
                                  for(int i=iF*offset; i<end; i++){
                                       a[i] = i;
                        threadList.add(t);
                   startTime = System.currentTimeMillis();
                   for(Thread t:threadList)
                        t.start();
                   for(Thread t:threadList)
                        t.join();
                   System.out.println("many threads List=" + (System.currentTimeMillis()-startTime));
    }Test3:
    package org.happy.concurrent.sort.forum;
    import java.util.ArrayList;
    import java.util.List;
    * simulates the array initialization in many threads on many arrays
    * @author Andreas Hollmann
    public class ArrayManyThreadsManyArrays {
         public static void main(String[] args) throws InterruptedException {
              final int arrayLength = (int)2e7;
              final int threadNumber = Runtime.getRuntime().availableProcessors();
              long startTime;
              final int offset = arrayLength/threadNumber;
                    * init many arrays in many threads
                   final ArrayList<Integer[]> list = new ArrayList<Integer[]>();
                   for(int i=0; i<threadNumber; i++){
                        int size = offset;
                        if(i<(threadNumber-1))
                             size = offset + arrayLength%threadNumber;
                        list.add(new Integer[size]);
                   List<Thread> threadList = new ArrayList<Thread>();
                   for(int i=0; i<threadNumber; i++){
                        final int index = i;
                        Thread t = new Thread(new Runnable(){
                             @Override
                             public void run() {
                                  Integer[] a = list.get(index);
                                  int value = index*offset;
                                  for(int i=0; i<a.length; i++){
                                       value++;
                                       a[i] = value;
                        threadList.add(t);
                   startTime = System.currentTimeMillis();
                   for(Thread t:threadList)
                        t.start();
                   for(Thread t:threadList)
                        t.join();
                   System.out.println("many threads - many List=" + (System.currentTimeMillis()-startTime));
    }

  • Mapping Java Arrays

    I was given an object model generated by an apache product, Axis. The generated java files use the Java Array in the following fashion:
    Class Zoo {
    private ArrayOfAnimals animals;
    // … public get/set methods cut
    Class ArrayOfAnimals {
    private Animal animals[];
    // … public get/set methods cut
    Class Animal {
    private String name;
    // … public get/set methods cut
    I was tasked with mapping the one-to-many relationship between zoo and an array of animals using the Animal array. I can’t find a mapping in TopLink to do this type of association. I am NOT allowed to modify the generated source code. I may be able to extend the generated classes, and perhaps provide a different superclass.
    I am allowed to create the relational model for these domain classes. Can anyone help with this type of mapping?
    Thanks

    TopLink does not directly support arrays as the mapping type for a collection, only collection types that support the Collection and Map interfaces.
    In general it seems odd to use an array instead of a Java collection which would be much more efficient (in terms of adding and removing) and much more functional. I would definitely suggest changing the generated code, or the way the code is generated if at all possible.
    The easiest way to map the array in TopLink would be the use get/set methods for the 1-m mapping on the Zoo class that converted the array to/from a Collection.
    i.e. something like,
    public List getAnimalsList() {
    return new Arrays.asList(animals.animals);
    public void setAnimalsList(List list) {
    animals.animals = (Animal[]) list.toArray();
    In general TopLink uses its ContainerPolicy class to handle collections. It may also be possible (but advanced) to write a custom container policy for your 1-m mapping that handles arrays.

  • Java.lag out of memory error

    my x2 cannot work with the pdf reader i downloaded from nokia store as there is java.lag out of memory error what should i do

    it is common in most s40 phones.....even my C3 does thesame

  • Conversion of java Array to oracle SQL Array while calling Stored Procedure

    How java Array can be converted to oracle SQL array while calling Stored procedure with callable statement.
    i.e java Array ---> Sql Array in Oracle while setting the datatypes to callable statement arguments.

    Look at:
    http://forum.java.sun.com/thread.jsp?forum=48&thread=376735&tstart=0&trange=15
    Paul

  • How to call a C sort function to sort a Java Array.

    My name is David, I'm interning this summer doing some High Performance Computing work. I'm significantly out of my comfort zone here; I am primarily a network/network security geek, not a programming guy. I took one Java based class called problem solving with programming where we wrote like 3 programs in Java and did everything else in pseudocode and using a program called Alice http://www.alice.org/ to do things graphically. Learned basically no actual programming syntax. Also have done some self-taught perl, but only through one book and I didn't finish it, I only got about half way through it. So my expertise in programming are pretty much null.
    That being said, I currently am tasked with having to figure out how to make JNI work... specifically at this time I am tasked with writing an array in Java, and designing a C program that can be called by means of JNI to sort the array. I have chosen to work with the Merge Sort algorithm. My method of coding is not one where I write the entire thing from scratch, I don't particularly have a need to master languages at this point, rather I just need to make them work. I am interested in learning, but time is of the essence for me right now. So thus far what I have done is take sample codes and tweak them to meet my purpose. However, I currently am unable to make things work. So I am asking for help.
    I am going to paste 3 codes here, the first one will be my basic self-written instructions for JNI (Hello World Instructions), the second one will be my Java Array, and the third one will be my MergeSort function. I am not asking for you to DO my work for me by telling me how to manipulate my code, but rather I am asking for you to send me in the direction of resources that will be of some aid to me. Links, books (preferrably e-books so I don't have to go to a library), anything that you can send my direction that may help will be deeply appreciated. Thanks so much!
    JNI Instructions:
    /*The process for calling a C function in Java is as follows:
    1)Write the Java Program name. Eg. HelloWorld.java
    2)Compile it: javac HelloWorld.java
    3)Create a header file: javah -jni HelloWorld
    4)Create a C program eg. HelloWorld.java
    5)Compile the C program creating a shared library eg. libhello.so (My specifc command is cc -m32 -I/usr/java/jdk1.7.0_05/include -I/usr/java/jdk1.7.0_05/include/linux -shared -o libhello.so -fPIC HelloWorld.c
    6) Copy the library to the java.library.path, or LD_LIBRARY_PATH (in my case I have set it to /usr/local/lib.
    7)Run ldconfig (/sbin/ldconfig)
    8)Run the java program: java HelloWorld. */
    //Writing the code:
    //For the HelloWorld program:
    //In java:
    //You need to name a class:
    class HelloWorld {
    //You then need to declare a native method:
    public native void displayHelloWorld();
    //You now need a static initializer:
    static {
    //Load the library:
    System.loadLibrary("hello");
    /*Main function to call the native method (call the C code)*/
    public static void main(String[] args) {
    new HelloWorld().displayHelloWorld();
    //In C:
    #include <jni.h> //JNI header
    #include "HelloWorld.h" //Header created by the javah -jni command parameter
    #include <stdio.h> //Standard input/output header for C.
    //Now we must use a portion of the code provided by the JNI header.
    JNIEXPORT void JNICALL
    Java_HelloWorld_displayHelloWorld(JNIENV *env, jobject obj)
    //Naming convention: Java_JavaProgramName_displayCProgramName
        printf("Hello World!\n");
        return;
    }Java Array:
    class JavaArray {
         private native int MergeSort(int[] arr);
         public static void main(String[] args)
             int arr[] = {7, 8, 6, 3, 1, 19, 20, 13, 27, 4};
         static
             System.loadLibrary("MergeSort");
    }Hacked and pieced together crappy C Merge Sort code:
    #include <jni.h>
    #include <stdio.h>
    #include "JavaArray.h"
    JNIEXPORT jint JNICALL
    Java_JavaArray_MergeSort(JNIEnv *env, jobject obj, jintArray arr[],jint low,jint mid,jint high)
       jint i,j,k,l,b[10];
    l=low;
    i=low;
    j=mid+1;
    while((l<=mid)&&(j<=high))
        if(arr[l]<=arr[j])
           b=arr[l];
    l++;
    else
    b[i]=arr[j];
    j++;
    i++;
    if(l>mid)
    for(k=j;k<=high;k++)
    b[i]=arr[k];
    i++;
    else
    for(k=l;k<=mid;k++)
    b[i]=arr[k];
    i++;
    for(k=low;k<=high;k++)
    arr[k]=b[k];
    void partition(jint arr[],jint low,jint high)
    jint mid;
    if(low<high)
    mid=(low+high)/2;
    partition(arr,low,mid);
    partition(arr,mid+1,high);
    sort(arr,low,mid,high);

    You're doing OK so far up to here:
    Java_JavaArray_MergeSort(JNIEnv *env, jobject obj, jintArray arr[],jint low,jint mid,jint high)This is not correct. It is not what was generated by javah. It would have generated this:
    Java_JavaArray_MergeSort(JNIEnv *env, jobject obj, jintArray arr,jint low,jint mid,jint high)A 'jintArray' is already an array, embedded in an object. You don't have an array of them.
    So you need to restore that, and the header file, the way 'javah' generated them, then adjust your code to call GetIntArrayElements() to get the elements out of 'arr' into a local int[] array, sort that, and then call ReleaseIntArrayElements() to put them back.

  • Manipulating java array object in an oracle procedure

    hi there,
    i have a java store procedure that returns an array of filenames, and i have an oracle stored procedure that will for each filename returned in the java array object, open that file do some processing and load the data into database tables, now my question is, would an oracle 9i varray object be compatible with a java array, or should i pass in a pl/sql table to store the filnames returned?
    i really am stuck at this point and need help !!!!
    Thanx

    Wole,
    Have you searched the code samples available at the Technet Web site? Could you not find a relevant one?
    Have you tried searching the Ask Tom Web site?
    Good Luck,
    Avi.

  • Java Array Out Of Bounds Problem

    In order to conduct an experiment in java array sorting algorithm efficiency, i am attempting to create and populate an empty array of 1000 elements with random, unique integers for sorting. I've been able to generate and populate an array with random integers but the problem is - for whatever size array I create, it only allows the range of numbers to populate it to be the size of the array, for instance, an array of size 3000 allows only the integer range of 0-3000 to populate it with or I get an out of bounds exception during runtime. How can you specify an integer range of say 0-5000 for an array of size < 5000? Any help is appreciated.

    Another approach is to fill the array with an
    arithmetic sequence, maybe plus some random noise:
        array[i] = i * k + rand(k);or some such, so they are unique,
    and then permute the array (put the elements
    s in random order)
        for (i : array.length) {
    transpose(array, array[rand(i..length)]); }
    Along those lines, java.util.Collections.shuffle can be used to randomly shuffle a List (such as an ArrayList).  Create an ArrayList with numbers in whatever range is needed.  Then call java.util.Collections.shuffle(myArrayList). [It is static in Collections--you don't need to [and can't] create a Collections object.]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to declare normal java array in fx

    How can we declare normal java array in fx. lets say I extend an abstract java class and it has a method which takes String array as parameter: abstract public void met(String[] users) ;How can i declare String[] parameter while overriding this abstract method in javafx. This does not work: override public function met(s:String[]){ ... }

    Hi,
    The code below works for me:
    public function run(args:String[]){
         var s:String[] = ["Hi", "Hello", "Love", "Peace"];     
         var t:Test2 = Test2{};     
         t.met(s);
    public abstract class Test{
         public abstract function met(s:String[]):Void;
    class Test2 extends Test{
         public override function met(s:String[]):Void{
              for(x in s){
                   println(x);
    }[]'s

  • The Mysterious java array implementation

    In java when we create an array of primitive data type
    e.g long[] x = new long[10];
    we can reterieve the lenght of the array using x.length. Does someone know where this variable length is declared. As in java arrays are implemented as an Objects. Even i treid to find out the class reference variable "x" belongs to, and I came to know that it is "[J" and this class implements Cloneable and Seriaziable interface. But there is no field or variable like "length".                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Java-Aspirant wrote:
    . Even i treid to find out the class reference variable "x" belongs to, and I came to know that it is "[J" and this class implements Cloneable and Seriaziable interface. But there is no field or variable like "length".
    If you want to use reflection on arrays, there's  [java.lang.reflect.Array|http://java.sun.com/javase/6/docs/api/java/lang/reflect/Array.html which allows you to interrogate the length pseudo-field and access elements.

  • How to figure out the size of an object - java out of heap memory error

    Hi all,
    I am using an object that I found in a library that I didn't create so I don't know its internal state or members.
    I created a single one of these objects and I call announce() on this object which just sends a UDP announcement over the channel to notify listeners. However, after a message #124,288 I get a java out of heap memory error.
    I am wondering if this announce() method is causing the state of the object to grow with every call...it seems unlikely but I want to check to see if it's reserving a growing amount of heap memory without ever allowing it to free.
    My question is how can I check how big the object is within my program? I'd like to check, for instance, at every 10,000 messages sent how much memory the object is taking up. Is there a method call for that? Would I have to use some kind of debugger or memory monitor? I would like something easy to use.
    Please let me know, and thanks in advance.
    Julian

    jboolean23 wrote:
    Thanks for the quick reply.
    I say it's unlikely that the methods I call are filling up heap memory because I have one Message object. This one Message has a myMsg String member. Whenever I want to change the message I call myMsg = "anewstringhere". And then I do myMessageObject.announce(); And for that reason i say I only have one Message object. The only thing added to the heap would be the strings that I replace myMsg with. The old references to myMsg are no longer valid and should be garbage collected..
    Unless of course if you are calling intern() on them.
    so here's my train of thought (and this isn't what my actual code looks like):
    myMessageObject.myMsg = "hello" //creates a string on the heap? I assume this is equivalent to saying myMsg = new String("hello")No they are not the same.
    The text literal will be in the intern space. Both code fragments would do that.
    The second example would create a second instance of String(). That second instance would be cleaned when no longer referenced. But the literal will not.
    Is my thought process correct? You are calling a third party library right so mock it (write a simple replacement that does the minimal correct functionality.) Substitute it in your code. And then run. If it still fails then the problem is in your code. If not then it is either in the library or the way that you use the library.

Maybe you are looking for