harmony-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From smish...@apache.org
Subject svn commit: r545554 [6/13] - in /harmony/enhanced/buildtest/branches/2.0/tests/reliability: ./ run/ src/ src/java/ src/java/org/ src/java/org/apache/ src/java/org/apache/harmony/ src/java/org/apache/harmony/test/ src/java/org/apache/harmony/test/reliab...
Date Fri, 08 Jun 2007 16:35:10 GMT
Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/ThreadSuspendResume/ThreadSuspendResume.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/ThreadSuspendResume/ThreadSuspendResume.java?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/ThreadSuspendResume/ThreadSuspendResume.java (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/ThreadSuspendResume/ThreadSuspendResume.java Fri Jun  8 09:34:52 2007
@@ -0,0 +1,341 @@
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Aleksey Ignatenko
+ * @version $Revision: 1.0 $
+ */
+
+package org.apache.harmony.test.reliability.api.kernel.thread.ThreadSuspendResume;
+
+import java.util.Random;
+import java.util.concurrent.TimeoutException;
+
+import org.apache.harmony.test.reliability.share.Test;
+import org.apache.harmony.test.reliability.share.Result;
+
+/**
+ *  Goal: check suspend/resume functionality in VM
+ *        The test does:
+ *        1. Reads parameters, which are:
+ *           param[0] - number of threads
+ *           param[1] - how many times to suspend/resume threads
+ *        2. Creates param[0]-sized array of threads and starts them. Threads are created 
+ *           twice: 1st as user threads, 2-nd - as daemon threads.
+ *           There are 4 kinds of created threads: 
+ *            a. math operations - does several java.lang.Math operations in a cycle 
+ *            b. math operations - does some simple calculations in a cycle
+ *            c. exceptions throwing - exceptions chosen by random are thwon in a cycle
+ *            d. synchronized sections - this type of thread contains 3 sinchronized sections,
+ *               2 sections contain wait-notify functionality.
+ *            - b,c are instrumented with sleep(0) function to allow main thread easily suspend
+ *              started threads (introduced suspend points into the code).
+ *           
+ *        3. Makes param[1] suspend/resume operations on started threads 
+ *        5. Calls .join() for each thread to sure that all threads have been killed
+ * 
+ *        No hang, fail or crash is excpected.
+ *    
+ */
+
+public class ThreadSuspendResume extends Test {
+    static final int NUMBER_OF_MILIS_WAITING = 30;
+    static final int NUMBER_OF_THREADS = 30;
+    static final int NUMBER_OF_ITERATIONS = 20; // suspend-resume iterations
+    static int numberOfIterations = NUMBER_OF_ITERATIONS;
+    static int numberOfThreads = NUMBER_OF_THREADS;
+    static final int NUMBER_OF_CASE_BLOCKS = 4;
+    volatile public static boolean failed = false; 
+    volatile public static boolean stopActivities = false;
+
+    public static void main(String[] args) {
+        System.exit(new ThreadSuspendResume().test(args));
+    }
+
+    public int test(String[] params) {
+        parseParams(params);
+        int res = testInternal(false);
+        if (res != Result.PASS){
+            return res;
+        }
+        res = testInternal(true);
+        if (res != Result.PASS){
+            return fail("FAILED");
+        }else{
+            return pass("OK");
+        }
+            
+    }
+    
+    int testInternal(boolean daemon){
+        Random rm = new Random();
+        // initialize variables of MonSynchThread 
+        MonSynchThread.mut1 = new Integer(1); 
+        MonSynchThread.mut2 = new Integer(2);
+        MonSynchThread.mut3 = new Integer(2);
+
+        
+        // create different type threads
+        Thread thrds[] = new Thread[numberOfThreads];
+        for (int k = 0; k < thrds.length; k++) {
+            switch (k%4){
+                case 0:
+                    thrds[k] = new ExceptionThrowThread();
+                    break;
+                case 1: 
+                    thrds[k] = new MonSynchThread();//ClassLoadingThread();
+                    break;
+                case 2:
+                    thrds[k] = new HardWorkingThreadSimple();
+                    break;
+                case 3:
+                    thrds[k] = new HardWorkingThread();
+                    break;
+            }
+            if (daemon == true){
+                thrds[k].setDaemon(true);
+            }
+        } 
+        
+        // start created threads
+        for (int k = 0; k < thrds.length; k++) {
+            thrds[k].start();
+        }
+        
+        // suspend/resume section
+        //System.out.println("Startign suspension/resuming");
+        int cycles = numberOfIterations * 2;
+        for (int j = 0; j<cycles; j++){
+            //System.out.println("Iteration " + j);
+            if (j%2 == 0){
+                for (int i = 0; i< thrds.length; i++){
+                    try{
+                        //System.out.println("Trying to suspend " + thrds[i].getId());
+                        thrds[i].suspend();
+                        try {
+                            Thread.currentThread().sleep(rm.nextInt(NUMBER_OF_MILIS_WAITING) + 1);
+                        } catch (InterruptedException e) {
+                            fail("Thread " +  thrds[i].getId() + " was interrupted");
+                        }                        
+                    } catch (SecurityException e){
+                        return fail("Failed to suspend thread " +  thrds[i].getId());
+                    }
+                }
+                System.gc();
+            } else{
+                for (int i = 0; i< thrds.length; i++){
+                    try{
+                        //System.out.println("Trying to resume " + thrds[i].getId());
+                        thrds[i].resume();
+                    } catch (SecurityException e){
+                        return fail("Failed to suspend thread " +  thrds[i].getId());
+                    }
+                }
+                System.gc();
+            }
+        }
+        
+        // stop threads
+        stopActivities = true;
+        
+        // join created threads
+        for (int k = 0; k < thrds.length; k++) {
+            try{
+                thrds[k].join();
+            }catch (InterruptedException ie) {
+                return fail("Failed to join thread " +  thrds[k].getId());
+            }
+        }
+        
+        if (failed == true){
+            return Result.FAIL;
+        }
+        return Result.PASS;
+    }
+
+    public void parseParams(String[] params) {
+        if (params.length >= 1) {
+            numberOfThreads = Integer.parseInt(params[0]);
+        }
+        if (params.length >= 2) {
+            numberOfIterations = Integer.parseInt(params[1]);
+        }
+    }
+
+}
+
+class HardWorkingThread extends Thread{
+    static final int MAX_ITER_NUMBER = 10000;
+    public void run(){
+        Random rm = new Random();
+        while (ThreadSuspendResume.stopActivities == false){
+            Math.log(rm.nextDouble());
+            Math.exp(rm.nextDouble());
+            Math.sqrt(rm.nextDouble());
+            Math.cos(rm.nextDouble());
+        }
+    }
+}
+
+
+class HardWorkingThreadSimple extends Thread{
+    static final int MAX_ITER_NUMBER = 10000;
+    public void run(){
+
+        while (ThreadSuspendResume.stopActivities == false){
+            long l = 0;
+            for (int i = 0; i < (MAX_ITER_NUMBER - 1) ; i++){
+                l += i;
+                l *= i;
+                long g = l%(i+1);
+                if (g == 0){
+                    g++;
+                }
+                double k = l/g;
+                double h = k/3.14;
+            }
+        }
+    }
+}
+
+class ExceptionThrowThread extends Thread{
+    public void run(){
+        while (ThreadSuspendResume.stopActivities == false){
+            try{
+                sleep(1);
+                genNextException();
+            }catch(Exception e){
+                try {
+                    sleep(1);
+                    genNextException();
+                } catch (Exception ex) {
+                    // Expected
+                    // do something                        
+                }
+                // do something
+                e.getLocalizedMessage();
+                e.getStackTrace();
+            }
+        }
+    }
+    void genNextException() throws Exception{
+        Random rm = new Random();
+        int choice = rm.nextInt(5);
+        switch(choice){
+            case 0:
+                throw new TimeoutException();
+            case 1:
+                throw new IllegalAccessException();
+            case 2:
+                int t= 10;
+                int z = 7/(10 -t);
+                System.out.println(z);
+                ThreadSuspendResume.log.add("Failed to throw exception case 4");
+                ThreadSuspendResume.failed = true;
+                break;
+            case 3:
+                char b[] = new char[10];
+                b[b.length] = 0; // ArrayIndexOutOfBoundsException 
+                ThreadSuspendResume.log.add("Failed to throw exception case 5");
+                ThreadSuspendResume.failed = true;
+                break;
+            case 4:
+                // throw nothing
+                break;
+            default:
+                throw new RuntimeException();
+        }
+    }
+}
+
+    // Test on basic synchronisation logic 
+class MonSynchThread extends Thread{
+    static final int THREAD_WAIT_TIME = 100;
+    static Object mut1 = null; 
+    static Object mut2 = null;
+    static Object mut3 = null;
+
+    public void run(){
+        
+        while (ThreadSuspendResume.stopActivities == false){
+            try{
+                sleep(1);
+            }catch(Exception e){
+                ThreadSuspendResume.log.add("Thread " + this.getId() + " was interrupted.");
+                ThreadSuspendResume.failed = true;
+                break;
+            }
+
+            // go through synchronized, 1-st passed wait calls notifyAll()  
+            synchronized(mut1){
+                
+                try {
+                    mut1.wait(THREAD_WAIT_TIME);
+                } catch (InterruptedException e) {
+                    ThreadSuspendResume.log.add("Thread " + this.getId() + " was interrupted.");
+                    ThreadSuspendResume.failed = true;
+                    break;
+                }
+            
+                mut1.notifyAll();
+            }
+
+            try{
+                sleep(1);
+            }catch(Exception e){
+                ThreadSuspendResume.log.add("Thread " + this.getId() + " was interrupted.");
+                ThreadSuspendResume.failed = true;
+                break;
+            }
+            
+            // go through synchronized, every passed calls notify()
+            synchronized(mut2){
+                
+                try {
+                    mut2.wait(THREAD_WAIT_TIME);
+                } catch (InterruptedException e) {
+                    ThreadSuspendResume.log.add("Thread " + this.getId() + " was interrupted.");
+                    ThreadSuspendResume.failed = true;
+                    break;
+                }
+            
+                mut2.notify();
+            }
+
+            // simple synchronization
+            synchronized(mut3){
+                try{
+                    sleep(1);
+                }catch(Exception e){
+                    ThreadSuspendResume.log.add("Thread " + this.getId() + " was interrupted.");
+                    ThreadSuspendResume.failed = true;
+                    break;
+                }
+                //
+                int c = 100;
+                int k = 0; 
+                while((c--) > 0){
+                    int i = 100;
+                    int j = 200;
+                    k /= (i*j);
+                }
+            }
+            
+        }
+    }
+}
+

Propchange: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/ThreadSuspendResume/ThreadSuspendResume.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/VolatileVariableTest/DekkerTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/VolatileVariableTest/DekkerTest.java?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/VolatileVariableTest/DekkerTest.java (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/VolatileVariableTest/DekkerTest.java Fri Jun  8 09:34:52 2007
@@ -0,0 +1,207 @@
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Igor A. Pyankov
+ * @version $Revision: 1.6 $
+ */
+
+package org.apache.harmony.test.reliability.api.kernel.thread.VolatileVariableTest;
+
+import org.apache.harmony.test.reliability.share.Test;
+
+/**
+ * Goal: check that VM supports volatile variables.
+ * 
+ * The test implements well-known concurrent programming algorithm for mutual
+ * exclusion by T.J.Dekker. (http://en.wikipedia.org/wiki/Dekker's_algorithm)
+ * 
+ * The test does: 1. Reads parameter, which is: param[0] - number of iterations
+ * to run critical region in each thread 2. Starts and, then, joins all started
+ * threads
+ * 
+ * 3. Checks that in each thread all checks PASSed.
+ * 
+ * 4. Each thread, being started: a. Runs param[0] iterations in a cycle, on
+ * each iteration: b. Checks the flag c. Changes flag when receive control d.
+ * Runs critical regoin of code
+ * 
+ */
+public class DekkerTest extends Test {
+    public int NUMBER_OF_ITERATIONS = 100;
+
+    public int[] statuses = { DStatus.PASS, DStatus.PASS };
+
+    public volatile long commonVar = 0;
+
+    public static volatile int started;
+
+    public static void main(String[] args) {
+        System.exit(new DekkerTest().test(args));
+    }
+
+    public int test(String[] params) {
+        parseParams(params);
+
+        Dekkerthread th0 = new Dekkerthread("0", this);
+        Dekkerthread th1 = new Dekkerthread("1", this);
+        started = 0;
+        th0.start();
+        th1.start();
+        while (started < 2) {
+        }
+        ;
+
+        try {
+            th0.join();
+            // log.add("Thread #0 joined()");
+            th1.join();
+            // log.add("Thread #1 joined()");
+        } catch (InterruptedException ie) {
+            return fail("interruptedException while join of threads");
+        }
+
+        // For each thread check whether operations PASSed in the thread
+        for (int i = 0; i < statuses.length; ++i) {
+            if (statuses[i] != DStatus.PASS) {
+                return fail("Status of thread " + i + ": is FAIL");
+            }
+            // log.add("Status of thread " + i + ": is PASS");
+        }
+        return pass("OK");
+    }
+
+    public void parseParams(String[] params) {
+        if (params.length >= 1) {
+            NUMBER_OF_ITERATIONS = Integer.parseInt(params[0]);
+        }
+    }
+
+}
+
+class Dekkerthread extends Thread {
+    volatile static boolean flag0 = false;
+
+    volatile static boolean flag1 = false;
+
+    volatile static int worker; // working thread number
+
+    static long[] vars = { 0x00000000FFFFFFFFL, 0xFFFFFFFF00000000L };
+
+    private int threadNum;
+
+    private int threadIteration;
+
+    private DekkerTest base;
+
+    public Dekkerthread(String arg, DekkerTest test) {
+        super();
+        if (arg.equals("0")) {
+            threadNum = 0;
+        } else {
+            threadNum = 1;
+        }
+        threadIteration = test.NUMBER_OF_ITERATIONS;
+        base = test;
+    }
+
+    /*
+     * check and close (if posible) semaphore before critical region of code
+     */
+    public void regionIn(int current) {
+        if (current == 0) {
+            flag0 = true;
+        } else {
+            flag1 = true;
+        }
+
+        int j = 1 - current;
+        if (j == 0) {
+            while (flag0) {
+                if (current != worker) {
+                    if (current == 0) {
+                        flag0 = false;
+                    } else {
+                        flag1 = false;
+                    }
+                    while (current != worker) {
+                    }
+                    if (current == 0) {
+                        flag0 = true;
+                    } else {
+                        flag1 = true;
+                    }
+                }
+            }
+        } else {
+            while (flag1) {
+                if (current != worker) {
+                    if (current == 0) {
+                        flag0 = false;
+                    } else {
+                        flag1 = false;
+                    }
+                    while (current != worker) {
+                    }
+                    if (current == 0) {
+                        flag0 = true;
+                    } else {
+                        flag1 = true;
+                    }
+                }
+            }
+        }
+
+    }
+
+    /* open semaphore after critical region of code */
+    public void regionOut(int current) {
+        worker = 1 - current; // change working thread
+        if (current == 0) {
+            flag0 = false;
+        } else {
+            flag1 = false;
+        }
+    }
+
+    public void run() {
+
+        // base.log.add("Thread #" + threadNum + " started " + threadIteration);
+        DekkerTest.started++;
+        while (threadIteration-- > 0) {
+            regionIn(threadNum);
+            // critical region
+
+            base.commonVar = vars[threadNum];
+            Thread.yield(); // to give a chance to another thread
+            if (base.commonVar != vars[threadNum]) {
+                base.statuses[threadNum] = DStatus.FAIL;
+                return;
+            }
+            // end of critical region
+            regionOut(threadNum);
+        }
+
+        // base.log.add("Thread #" + threadNum + " finished ");
+    }
+}
+
+class DStatus {
+    public static final int FAIL = -10;
+
+    public static final int PASS = 10;
+}

Propchange: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/VolatileVariableTest/DekkerTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/VolatileVariableTest/PetersonTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/VolatileVariableTest/PetersonTest.java?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/VolatileVariableTest/PetersonTest.java (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/VolatileVariableTest/PetersonTest.java Fri Jun  8 09:34:52 2007
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Igor A. Pyankov
+ * @version $Revision: 1.4 $
+ */
+
+package org.apache.harmony.test.reliability.api.kernel.thread.VolatileVariableTest;
+import org.apache.harmony.test.reliability.share.Test;
+
+/**
+ *  Goal: check that VM supports volatile variables
+ *  
+ *  The test implements well-known concurrent programming algorithm 
+ *  for mutual exclusion by G.Peterson.
+ *  (http://en.wikipedia.org/wiki/Peterson%27s_algorithm)
+ *
+ *  The test does:
+ *     1. Reads parameter, which is:
+ *            param[0] - number of iterations to run critical region in each thread
+ *     2. Starts and, then, joins all started threads
+ *
+ *     3. Checks that in each thread all checks PASSed.
+ *
+ *     4. Each thread, being started:
+ *         a. Runs param[0] iterations in a cycle, on each iteration:
+ *         b. Checks the flag
+ *         c. Changes flag when receive control
+ *         d. Runs critical regoin of code
+ *
+ */
+
+
+public class PetersonTest extends Test {
+    public int NUMBER_OF_ITERATIONS = 100;
+    public int[] statuses = {PStatus.PASS, PStatus.PASS};
+    volatile public long commonVar = 0;
+    volatile public static int finished;
+    
+    public static void main(String[] args) {
+        System.exit(new PetersonTest().test(args));
+    }
+
+    public int test(String[] params) {    
+        parseParams(params);
+
+        Petersonthread th0 = new Petersonthread(0, this);
+        Petersonthread th1 = new Petersonthread(1, this);
+        finished = 2;
+        th0.start();
+        th1.start();
+        while(finished > 0) {
+            Thread.yield();    
+        };
+        
+        // For each thread check whether operations PASSed in the thread
+        for (int i = 0; i < statuses.length; ++i){
+            if (statuses[i] != PStatus.PASS){
+                return fail("Status of thread " + i + ": is FAIL");
+            }
+            // log.add("Status of thread " + i + ": is PASS");
+        }
+        return pass("OK");
+
+    }
+
+
+    public void parseParams(String[] params) {
+        if (params.length >= 1) {
+            NUMBER_OF_ITERATIONS = Integer.parseInt(params[0]);
+        }                                                   
+    }
+
+}
+
+
+class Petersonthread extends Thread {
+
+    volatile static int[] flags = { 0, 0 };
+    volatile static int worker; // working thread number
+
+    static long[] vars = {0x00000000FFFFFFFFL, 0xFFFFFFFF00000000L};
+    private int threadNum;
+    private int threadIteration;
+    private PetersonTest base;
+
+    public Petersonthread(int num, PetersonTest test) {
+        super();
+        threadNum = num;
+        threadIteration = test.NUMBER_OF_ITERATIONS;
+        base = test;
+    }
+
+    /*
+     * check and close (if posible) semaphore before critical region of code
+     */
+    public void regionIn(int current) {
+        flags[current] = 1;
+        int j = 1 - current;
+        worker = j;
+        while ((flags[j] == 1) && worker == j) {}
+    }
+
+    /* open semaphore after critical region of code */
+    public void regionOut(int current) {
+        flags[current] = 0;
+    }
+
+    public void run() {
+        // base.log.add("Thread #" + threadNum + " started " + threadIteration);
+
+        while (threadIteration-- > 0) {
+            regionIn(threadNum);
+
+            // critical region
+            base.commonVar = vars[threadNum];
+            Thread.yield(); //to give a chance to another thread
+
+            if (base.commonVar != vars[threadNum]) {
+                base.statuses[threadNum] = PStatus.FAIL;
+                return;
+            }
+
+            // end of critical region
+            regionOut(threadNum);
+        }
+        worker = 1 - threadNum;
+        // base.log.add("Thread #" + threadNum + " finished ");
+        PetersonTest.finished--;
+    }
+}
+
+
+class PStatus {
+    public static final int FAIL = -10;
+    public static final int PASS = 10;
+}
+
+
+

Propchange: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/VolatileVariableTest/PetersonTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/WeakReferenceandThreadTest/WeakReferenceandThreadTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/WeakReferenceandThreadTest/WeakReferenceandThreadTest.java?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/WeakReferenceandThreadTest/WeakReferenceandThreadTest.java (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/WeakReferenceandThreadTest/WeakReferenceandThreadTest.java Fri Jun  8 09:34:52 2007
@@ -0,0 +1,158 @@
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Igor A. Pyankov
+ * @version $Revision: 1.2 $
+ *
+ */
+package org.apache.harmony.test.reliability.api.kernel.thread.WeakReferenceandThreadTest;
+
+import org.apache.harmony.test.reliability.share.Test;
+import java.lang.ref.WeakReference;
+
+/**
+ *   Goal: check that GC correctly works with weak reference variables 
+ *   The test does:
+ *             1. Reads parameter, which is:
+ *                param[0] - number of starting threads
+ *                param[1] - number of attemps to call GC
+ *                   
+ *             2. Starts param[0] threads
+ * 
+ *             3. Each thread creates obejct, gets weak reference to the object,
+ *                clear strong reference to tht object and call GC param[1] times.
+ *                Weak reference must be cleaned.
+ * 
+ *             4. Checks that each thread died and has status PASS.
+ *      
+ */
+public class WeakReferenceandThreadTest extends Test {
+
+    private static int NUMBER_OF_THREADS = 120;
+    public static int[] status;
+    public static int ATTEMPTS = 10;
+
+    public static volatile boolean started = false;
+
+    public static void main(String[] args) {
+        System.exit(new WeakReferenceandThreadTest().test(args));
+    }
+
+    public WeakReferenceandThreadTest() {
+        super();
+    }
+
+    public int test(String[] params) {
+        boolean passed = true;
+        int numberAlive = NUMBER_OF_THREADS;
+        parseParams(params);
+        status = new int[NUMBER_OF_THREADS];
+        Thread t[] = new Thread[NUMBER_OF_THREADS];
+
+        for (int i = 0; i < NUMBER_OF_THREADS; i++) {
+            t[i] = new RefCreater(i);
+            t[i].start();
+        }
+
+        while (!started) {}; 
+
+        while (numberAlive > 0) {
+            numberAlive = 0;
+            for (int k = 0; k < NUMBER_OF_THREADS; k++) {
+                if (t[k].isAlive()) {
+                    numberAlive++;
+                }
+                //Thread.yield();
+            }
+            //log.add("na " + numberAlive);
+        }
+
+        for (int k = 0; k < NUMBER_OF_THREADS; k++) {
+            if (status[k] != WStatus.PASS) {
+                log.add("Status of thread " + k + " is " + status[k]);
+                passed = false;
+            }
+        }
+
+        if (passed) {
+            return pass("OK");
+        } else {
+            return fail("Test failed");
+        }
+    }
+
+    public void parseParams(String[] params) {
+        if (params.length >= 1) {
+            NUMBER_OF_THREADS = Integer.parseInt(params[0]);
+            if (params.length >= 2) {
+                ATTEMPTS = Integer.parseInt(params[1]);
+            }
+        }
+    }
+
+}
+
+class RefCreater extends Thread {
+    private int number; // Thread number
+
+    public RefCreater(int number) {
+        this.number = number;
+    }
+
+    public void run() {      
+        // the signal - thread started.
+        WeakReferenceandThreadTest.started = true; 
+          
+        Long obj = new Long(number);
+        WeakReference wr = new WeakReference(obj);
+        obj = null;
+
+        try {
+            if (((Long) wr.get()).intValue() != number) {
+                // no referent
+                WeakReferenceandThreadTest.status[number] = WStatus.FAIL1;
+                return;
+            }
+        } catch (NullPointerException npe) {
+            WeakReferenceandThreadTest.status[number] = WStatus.PASS;
+            return;
+        }
+
+        for (int i = 0; i < WeakReferenceandThreadTest.ATTEMPTS; i++) {
+            System.gc();
+            Thread.yield();
+
+            if (wr.get() == null) {
+                // // Weak reference cleared
+                WeakReferenceandThreadTest.status[number] = WStatus.PASS;
+                return;
+            }
+
+            // Weak reference was not cleared after number attempts
+            WeakReferenceandThreadTest.status[number] = WStatus.FAIL2;
+            return;
+        }
+    }
+}
+
+
+class WStatus {
+    public static final int FAIL1 = -1; // no referent created
+    public static final int FAIL2 = -2; // weakreference was not cleared
+    public static final int PASS = 1;   // ok
+}

Propchange: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/thread/WeakReferenceandThreadTest/WeakReferenceandThreadTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/threadgroup/EnumerateTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/threadgroup/EnumerateTest.java?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/threadgroup/EnumerateTest.java (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/threadgroup/EnumerateTest.java Fri Jun  8 09:34:52 2007
@@ -0,0 +1,337 @@
+/*
+ * Copyright 2007 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Oleg Oleinik
+ * @version $Revision: 1.1 $
+ */
+
+package org.apache.harmony.test.reliability.api.kernel.threadgroup;
+
+import org.apache.harmony.test.reliability.share.Test;
+import java.util.Random;
+
+/*
+ * Goal: check that ThreadGroup's enumerate(ThreadGroup, true), enumerate(Thread, true) 
+ *       and destroy() work without problems (crashes) in multi-threaded environment.
+ *
+ * The test does:
+ *   1. Reads parameters:
+ *      param[1] - number of direct subgroups of each ThreadGroup in the ThreadGroup tree
+ *      param[2] - number of Threads - direct childs of each ThreadGroup in the tree
+ *      param[3] - defines tree depth
+ *      param[4] - number of Threads calling enumerate() methods in parallel to working
+ *                 threads of the tree.
+ *      
+ *   2. Builds a tree of ThreadGroups and Threads:
+ *      - each ThreadGroup (but leaf ThreadGroup) has N_OF_SUBGROUPS child ThreadGroups
+ *      - in addition, each ThreadGroup has N_OF_THREADS child Threads
+ *      - tree depth is TREE_DEPTH + 1
+ *      - Threads are started and running
+ *      
+ *   3. Creates N_OF_ENUMERATING_THREADS "enumerating" Threads, each calling 
+ *      enumerate(ThreadGroup, true) and enumerate(Thread, true) in a cycle 
+ *      until there are no active Threads or all threads were supposedly finished. 
+ *      
+ *   4. When no active Threads remain, each "enumerating" Thread calls 
+ *      destroy() for the root ThreadGroup.
+ *   
+ *   5. Expected result: no crashes or hangs.
+ *   
+ */
+
+public class EnumerateTest extends Test {
+    
+    public static int N_OF_SUBGROUPS = 2;
+    public static int N_OF_THREADS = 2;
+    public static int TREE_DEPTH = 5;
+    
+    public static int N_OF_ENUMERATING_THREADS = 10;
+
+    public static void main(String[] args) {
+        System.exit(new EnumerateTest().test(args));
+    }
+
+    public int test(String[] params) {
+
+        parseParams(params);
+
+        // Two test calls:
+        // 1. ThreadGroups / Threads are daemons
+        // 2. ThreadGroups / Threads are non-daemons
+    
+        return (test(true) && test(false)) ? pass("OK") : fail("");
+    }
+
+    boolean test(boolean daemon) {
+    
+        ThreadCounter.clear(); // clear static counters of created and being running threads
+
+        ThreadGroup rootTG = new ThreadGroup("0");
+        
+        rootTG.setDaemon(daemon);
+       
+        // build ThreadGroup tree
+        new TGTreeBuilder().buildTree(rootTG, N_OF_SUBGROUPS, N_OF_THREADS, TREE_DEPTH);
+
+        // start "enumerating" threads
+        Thread[] t = new Thread[N_OF_ENUMERATING_THREADS];
+        
+        for (int i = 0; i < t.length; ++i){
+            t[i] = new EnumeratingThread(rootTG, i);
+            t[i].start();
+        }
+        
+        for (int i = 0; i < t.length; ++i){
+            try {
+                t[i].join();
+            } catch (InterruptedException ie) {
+                log.add("InterruptedException while join()-ing enumerating threads");
+                return false;
+            }
+        }
+
+        // finally, call destroy() expecting ITSE, since 'rootTG' is actually
+        // destroyed by one of enumerating threads
+        try {
+            rootTG.destroy();
+        } catch (IllegalThreadStateException itse){
+            // System.out.println("Main thread : IllegalThreadStateException");
+        }
+        
+        return true;
+    }
+    
+    public void parseParams(String[] params) {
+        
+        if (params.length >= 1) {
+            N_OF_SUBGROUPS = Integer.parseInt(params[0]);
+        }
+
+        if (params.length >= 2) {
+            N_OF_THREADS = Integer.parseInt(params[1]);
+        }
+
+        if (params.length >= 3) {
+            TREE_DEPTH = Integer.parseInt(params[2]);
+        }
+       
+        if (params.length >= 3) {
+            N_OF_ENUMERATING_THREADS = Integer.parseInt(params[3]);
+        }        
+    }
+}
+
+
+class EnumeratingThread extends Thread {
+
+    static Random Rnd = new Random(1);
+
+    ThreadGroup tg = null;
+    int ID = 0;
+
+    EnumeratingThread(ThreadGroup tg, int ID){
+        this.tg = tg;
+        this.ID = ID;
+    }
+
+    public void run() {
+
+        prioritize(tg);
+        
+        if (ID % 2 == 0) {
+            enumerateThreads(tg);
+            enumerateGroups(tg);
+        } else {
+            enumerateGroups(tg);
+            enumerateThreads(tg);
+        }
+
+        // Only one "enumerating" Thread will really destroy 'tg'...
+        while (!tg.isDestroyed()){
+            try {
+                tg.destroy();
+            } catch (IllegalThreadStateException itse){
+                Thread.yield();
+            }
+        }
+    }
+   
+    void prioritize(ThreadGroup tg) {
+        int prio = Thread.MIN_PRIORITY + Rnd.nextInt((Thread.MAX_PRIORITY - Thread.MIN_PRIORITY));
+        tg.setMaxPriority(prio);
+    }
+
+    void enumerateThreads(ThreadGroup tg) {
+        // We are actually not interested in receiving all Threads,
+        // instead, lets see what happens if we are interested only
+        // in one - won't there be problems with leaving Thread objects
+        // outside of array?
+        Thread[] t = new Thread[1];
+
+        // There is no synchronization between enumerating and being enumerated Threads 
+        // (intentionally).
+        // We enumerate active threads while less threads are/were actually run than 
+        // were created (to avoid situation that some threads were start()-ed but are not
+        // yet run()-ning and are not considered active), or there are still active threads,
+        // or, threads are not considered active (no clear definition of "active" in specification) 
+        // but not yet all finished.
+        
+        while(tg.enumerate(t, true) > 0 || tg.activeCount() > 0 || 
+            ThreadCounter.getRunning() < ThreadCounter.getCreated() ||
+            ThreadCounter.getFinishing() < ThreadCounter.getCreated()) {
+            Thread.yield();
+        }
+        // System.out.println("All threads finished " + ID);
+        
+        // At this point we can expect that all threads finished - all were run, 
+        // no active or running remains.
+    }
+
+    void enumerateGroups(ThreadGroup tg) {
+        // The same as with Threads - we are actually not interested in receiving all groups
+        ThreadGroup[] t = new ThreadGroup[1];
+        
+        tg.activeGroupCount(); // just in case, no specific purpose of this call
+        tg.enumerate(t, true);
+    }
+}
+
+
+class TGTreeBuilder {
+
+    // tree building is done via recursive invocation of buildTree(...)
+    
+    public void buildTree(ThreadGroup parent, int n_subgroups, int n_threads, int depth) {
+
+        // first, create threads which are direct childs of the 'parent'
+        createThreads(n_threads, parent);
+        
+        if (depth > 0) {
+            for (int i = 0; i < n_subgroups; ++i){
+                // second, create ThreadGroups which are direct childs of the 'parent'
+                ThreadGroup tg = new ThreadGroup(parent, "");
+                tg.setDaemon(parent.isDaemon());
+                // for each child ThreadGroup build a subtree
+                buildTree(tg, n_subgroups, n_threads, depth - 1);
+            }
+        }
+    }
+    
+    // Creates and starts n_threads of AThread class
+    public Thread[] createThreads(int n_threads, ThreadGroup parent){
+        Thread[] t = new Thread[n_threads]; 
+        for (int i = 0; i < t.length; ++i){
+            t[i] = new AThread(parent);
+            t[i].setDaemon(parent.isDaemon());
+            t[i].start();
+        }
+        return t;
+    }
+}
+
+    // AThread is just ordinary thread which should execute some time-consuming
+    // operations, no metter which. What is important that there is a chance that 
+    // "enumeration" threads call enumerate() while AThreads are active.
+
+class AThread extends Thread {
+
+    public AThread(ThreadGroup parent) {
+        super(parent, "");
+        ThreadCounter.incCreated();
+    }
+  
+    public void run() {
+        ThreadCounter.incRunning();
+        A.doSomething();
+        enumerate(new Thread[1]); // test call
+        ThreadCounter.incFinishing();
+    }
+}
+
+class A {
+
+    static int sizeI = 10;
+    static int sizeJ = 100;
+
+    static Random Rnd = new Random(1);
+ 
+    void setSize(int i, int j){
+        sizeI = i;
+        sizeJ = j;
+    }
+    
+    // The method just fills-in 2 dimensional String array with sleep()s
+    // between iterations. i.e. literally does something.
+    
+    static void doSomething(){
+    
+        String[][] str = new String[sizeI][sizeJ];
+        
+        for (int i = 0; i < str.length; ++i) {
+      
+            for (int j = 0; j < str[i].length; ++j) {
+                str[i][j] = "" + i + "" + j;
+            }
+        
+            Thread.yield();
+
+            int rnd = Rnd.nextInt(10);
+            try {
+                Thread.sleep(rnd);
+            } catch (InterruptedException ie) {
+            }
+        }
+    }
+}
+
+class ThreadCounter {
+
+    static volatile int running = 0;
+    static volatile int created = 0;
+    static volatile int finishing = 0;
+
+    static synchronized int getRunning() {
+        return running;
+    }
+
+    static synchronized int getCreated() {
+        return created;
+    }
+    
+    static synchronized int getFinishing() {
+        return finishing;
+    }
+
+    static synchronized void incRunning() {
+        ++running;
+    }
+  
+    static synchronized void incCreated() {
+        ++created;
+    }
+    
+    static synchronized void incFinishing() {
+        ++finishing;
+    }
+
+    static synchronized void clear() {
+        running = 0;
+        created = 0;
+        finishing = 0;
+    }
+}

Propchange: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/threadgroup/EnumerateTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/throwable/StackTraceExcptsTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/throwable/StackTraceExcptsTest.java?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/throwable/StackTraceExcptsTest.java (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/throwable/StackTraceExcptsTest.java Fri Jun  8 09:34:52 2007
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Nikolay Bannikov
+ * @version $Revision: 1.2 $
+ */
+
+package org.apache.harmony.test.reliability.api.kernel.throwable;
+
+import org.apache.harmony.test.reliability.share.Test;
+import java.util.Random;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+
+
+/**
+ *  Goal: find resource leaks or intermittent errors caused by operations with Exceptions
+ *        and methods of Throwable.
+ *        
+ *  Idea: A number of Threads is started, each starts recursive method which 
+ *        throws/catches exceptions, prints stack trace into own PrintWriter,
+ *        checks the length of exception cause chain.
+ *
+ *  The test does:
+ *      Creates and runs a Thread which calls runRecursiveException(..) method AND starts 
+ *      N_OF_THREADS of analoguous Threads.
+ *          
+ *      runRecursiveException(..) is recursive method 
+ *      which throws/catches exceptions. Recursion depth is defined by RECURSION_DEPTH.
+ *
+ */
+
+public class StackTraceExcptsTest extends Test {
+
+    static final int N_OF_THREADS = 1;
+
+    static final int RECURSION_DEPTH = 50;
+
+    public static void main(String[] args) {
+        System.exit(new StackTraceExcptsTest().test(args));
+    }
+
+
+    public int test(String[] params) {
+
+        Thread t = new ExceptionThrowingThread(RECURSION_DEPTH, 0);
+        t.start();
+
+        try {
+            t.join();
+        } catch (InterruptedException ie) {
+        }
+
+        return pass("OK");
+    }
+
+
+}
+
+
+class ExceptionThrowingThread extends Thread {
+
+    int depth = 0;
+    int id = -1;
+
+    ExceptionThrowingThread(int depth, int number){
+        this.depth = depth;
+        this.id = number;
+    }
+
+    public void run() {
+
+        if (depth == 0){
+            return;
+        }
+
+        // System.out.println(" Thread depth: " + depth + ", ID: " + id);
+
+        // Each Thread:
+        //   - starts N_OF_THREADS of the this Thread type
+        //   - starts exception-throwing runRecursiveException(..)
+
+        Thread[] t = new Thread[StackTraceExcptsTest.N_OF_THREADS];
+
+        for (int i = 0; i < t.length; ++i) {
+            t[i] = new ExceptionThrowingThread(depth - 1, i);
+            t[i].start();
+        }
+
+        try {
+
+            // Start recursive exception-throwing method from this thread.
+
+            runRecursiveException(depth - 1);
+
+        } catch (RuntimeException e) {
+
+            Throwable cause = e.getCause();
+
+            // This is actually a check - length of chain of causing exceptions
+            // should be 'depth - 2', if less, then, NPE will be thrown:
+
+            for (int i = 0; i < depth - 2; ++i) {
+                cause = ((RuntimeException) cause.getCause());
+            }
+        }
+
+        for (int i = 0; i < t.length; ++i) {
+            try {
+                t[i].join();
+            } catch (InterruptedException ie) {
+            }
+        }
+            
+    }
+
+    public int runRecursiveException(int depth) {
+
+        int i = 100;
+
+        // The method calls itself recursively. On each recursion level it
+        // expects (catches) RuntimeException thrown from lower level, then,
+        // re-throws new RuntimeException higher, specifies caught exception as cause.
+
+        if (depth > 0) {
+
+            try {
+
+                // R E C U R S I V E   C A L L:
+
+                runRecursiveException(depth - 1);
+
+            } catch (RuntimeException e) {
+
+                // We create a PrintWriter just to call printStackTrace(..) and then loose 
+                // reference to it. printStackTrace(..) is called to stimulate resource 
+                // leaks or intermittent errors:
+
+                PrintWriter pw = new PrintWriter(new StringWriter(), true);
+                e.printStackTrace(pw);
+                pw.flush();
+
+                // Throw RuntimeException upper, specify caught from lower level exception as cause:
+
+                RuntimeException re = new RuntimeException("" + depth + " caused by " + e.toString(), e);
+
+                re.fillInStackTrace();
+
+                throw re;
+            }
+
+        } else {
+
+            // depth is 0, causing ArithmeticException (division by zero), depth can not be < 0.
+
+            i = i / depth;
+        }
+
+        return i;
+    }
+
+}
+

Propchange: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/kernel/throwable/StackTraceExcptsTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/NetClient.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/NetClient.java?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/NetClient.java (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/NetClient.java Fri Jun  8 09:34:52 2007
@@ -0,0 +1,399 @@
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Nikolay V. Bannikov
+ * @version $Revision: 1.5 $
+ */
+
+package org.apache.harmony.test.reliability.api.net;
+
+import org.apache.harmony.test.reliability.share.Test;
+
+
+import java.io.BufferedReader;
+import java.io.PrintWriter;
+import java.io.FileInputStream;
+import java.io.InputStreamReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.StringReader;
+import java.io.OutputStreamWriter;
+import java.io.IOException;
+import java.io.FileNotFoundException;
+
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.ServerSocket;
+import java.net.UnknownHostException;
+
+/**
+ * Goal: find errors/failures of Networking API while intensive work
+ *       with socket servers/clients.
+ *
+ * The test does:
+ * 
+ * 1. There is golden file for reading from a server upon socket client requests.
+ * 
+ * 2. The socket server is created and run.
+ * 3. A lot of socket clients are created in thread and each of them try to 
+ *    connect to the server.
+ *    
+ * 4. After successful connection the client reads the golden file into a file 
+ *    created 'on the fly' and writes it in a directory.
+ * 
+ * 5. Then the file's content is compared with the golden file.
+ * 
+ * 6. The test passes is comparison is OK.
+ * 
+ * 7. All created file are deleted.
+ * 
+ */
+
+public class NetClient  extends Test {
+
+    public int THREAD = 4;
+    public static int CNT = 100;
+    public static int PORT = 8000;
+    public static String path_to_files;
+    public final static int SLEEP = 1000; 
+    ServerSocket server;
+
+    private Socket socket;
+    private BufferedReader bufReader, in;
+    private PrintWriter prnWriter;
+    private FileInputStream fis;
+    private static int clientcounter = 0;
+
+    private static int threadcnt = 0;
+    private static int cycle = 0;
+    private static String golden = "Test.out";
+    private static String golden_lnx = "Test_lnx.out";
+
+    private boolean result = true;
+    private String fileName = "";
+
+    private String separator = File.separator;
+    private String filedir = System.getProperty("java.io.tmpdir") + separator + "reliability_net";
+
+    public int threadcnt() {
+        return threadcnt;
+    }
+
+    public int cnt() {
+        return clientcounter;
+    }
+
+    public boolean result() {
+        return result;
+    }
+
+
+    public int test(String[] params) {
+
+        if (params.length >= 1) {
+            path_to_files =  params[1];
+        }        
+
+        if (params.length >= 2) {
+            PORT = Integer.parseInt(params[2]);
+        }        
+
+        PORT = PORT + cycle++;
+
+        if (params.length >= 0 && Integer.parseInt(params[0]) > 0) {
+            CNT = Integer.parseInt(params[0]);
+        }        
+
+        if (params.length >= 3 && Integer.parseInt(params[3]) > 0) {
+            THREAD =  Integer.parseInt(params[3]);
+        }
+        
+        if (!path_to_files.endsWith("auxiliary")) {
+            log.add("invalid path to the golden files");
+            return fail("Failed.");
+        }
+
+        if (params.length >= 4) {
+            golden = params[4];
+        }
+
+        //log.add("tmpdir = " + filedir);
+
+        File temp = new File(filedir);
+        temp.mkdir();
+        temp.deleteOnExit();
+
+        
+        //log.add("PORT = " + PORT++);
+
+        try {    
+            server = new ServerSocket(NetClient.PORT);
+            //log.add("Creates a server socket " + server + ", bound to the" + NetClient.PORT + " port");
+        }  catch (Exception e) {
+
+            log.add("Creates a ServerSocket(" + NetClient.PORT + "): Exception during test execution");
+            log.add(e);
+            return fail("Failed.");
+        }
+
+        // Listens for a connection to be made to socket and  read file        
+        Thread srv = new Thread(
+            new Runnable() {
+                public void run() {
+                    int i = 0;
+                    try {
+                        while(i != NetClient.CNT) {
+                            i++;
+                            Socket socket = null;
+                            socket = server.accept();                    
+                            new SockServer(socket);
+                        }
+                    }  catch (Exception e) {
+            
+                        log.add(e);
+                        log.add("Creates a SockServer" + i + ": Exception during test execution");
+
+                    } finally {
+                        try {
+                            server.close();
+                            //log.add("server closed");
+                        }  catch (IOException e) {
+                            log.add("Server closed: Exception during test execution");
+                            log.add(e);
+                        }
+                    }
+
+                }
+            }
+        );
+
+        srv.start();
+
+        InetAddress ia = null;
+
+        try {    
+            ia = InetAddress.getByName("localHost");
+
+        }  catch (UnknownHostException e) {
+        
+            log.add(e);
+            return fail("no IP address for the host");
+        }
+
+        //Creates some sockets and connects to the specified port 
+        while(true) {
+
+            if(threadcnt() < THREAD) {
+
+                Client client =  new Client(ia);
+            }
+
+            try {    
+                Thread.currentThread().sleep(NetClient.SLEEP);
+            }  catch (InterruptedException e) {
+                log.add(e);
+                return fail("another thread has interrupted the current thread");
+
+            }
+            if(cnt() == CNT) {
+                clientcounter = 0;
+                break;
+            }
+        }
+
+
+        if (result()) {
+            return pass("OK");
+        } else {
+            return fail("Failed.");
+        }
+    }
+
+
+    private class Client extends Thread {
+
+        private int id = clientcounter++;
+
+        public Client(InetAddress ia) {
+
+            threadcnt++;
+
+            try {
+                //log.add("Creates a new socket with IP address " + ia + " and connects it to the port " + NetClient.PORT);                                
+                socket = new Socket(ia, NetClient.PORT);
+            }  catch (Exception e) {
+
+                log.add(e);
+                log.add("error occurs when creating the Socket(ia, NetClient.PORT): Exception during test execution");
+
+            } 
+            try {
+
+                fileName = filedir + separator + "Test" + id + ".out";
+                bufReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
+                prnWriter = new PrintWriter(new BufferedWriter(new FileWriter(new File(fileName)))); 
+                start();
+
+            } catch (Exception e) {
+
+                log.add(e);
+                log.add("error occurs when writting to the " + fileName);
+
+                try {
+                    socket.close();
+                }  catch (Exception ee) {
+                    ee.printStackTrace();
+                }
+            }    
+        }
+        //two files to be tested for equality
+        public boolean checkFiles(String golden, String filename, BufferedReader bufReader, PrintWriter prnWriter, int buf) {
+
+            String str = new String();
+            File file = new File(fileName);
+            byte a[] = new byte[buf];
+            byte b[] = new byte[buf];
+            // read lines from BufferedReader and write to the file
+            try {
+                while((str = bufReader.readLine()) != null) {
+                    prnWriter.println(str);
+                }
+            }  catch (IOException e) {
+                log.add(e);
+                log.add("error occurs when reading line from file" + fileName);
+            } finally {
+                try {
+                    prnWriter.close();
+                    bufReader.close();
+                }  catch (IOException e) {
+                    log.add(e);
+                }
+            }
+            // write golden file to the array
+            try {
+                fis = new FileInputStream(golden);
+                fis.read(a);
+            }  catch (FileNotFoundException e) {
+                log.add(e);
+                log.add("The file " + golden + "does not exist");
+            }  catch (IOException ee) {
+                log.add(ee);
+                log.add("error occurs when reading byte a[] from  file" + golden);
+            } finally {
+                try {
+                    fis.close();
+                }  catch (IOException e) {
+                    log.add(e);
+                }
+            }
+            // write a file to the array
+            try {
+                fis = new FileInputStream(file);
+                fis.read(b);
+            }  catch (FileNotFoundException e) {
+                log.add(e);
+                log.add("The file " + fileName + "does not exist");
+            }  catch (IOException ee) {
+                log.add(ee);
+                log.add("error occurs when reading byte b[] from  file" + fileName);
+            } finally {
+                try {
+                    fis.close();
+                    socket.close();
+                }  catch (IOException e) {
+                    log.add(e);
+                }
+                threadcnt--;
+            }
+
+            // arrays to be tested for equality
+            if(java.util.Arrays.equals(a, b)) {
+                //log.add("checks "+ filename + " : true");
+                return true;
+            } else {
+                log.add("checks "+ filename + " : false");        
+                return false;
+            }
+        }
+
+        public void run() {
+
+            String pathtogolden = NetClient.path_to_files + separator +  golden;
+            if(System.getProperty("os.name").indexOf("Windows") == -1) {
+                pathtogolden = NetClient.path_to_files + separator +  golden_lnx;
+            }
+            if(!checkFiles(pathtogolden, fileName, bufReader, prnWriter, 10000)) {
+                result = false;
+                log.add("checks the file " + fileName + ": FAILED");
+            }
+            new File(fileName).delete();
+        }  
+    }
+
+    private class SockServer extends Thread {
+
+        private Socket socket;
+        private BufferedReader bufReader, in;
+        private PrintWriter prnWriter;
+
+        public SockServer(Socket s) throws Exception {
+            socket = s;
+            //log.add("read text from the golden file");
+            in =new  BufferedReader(new FileReader(NetClient.path_to_files + File.separator + golden));
+            String str1 = new String();
+            String str2 = new String();
+            while((str1 = in.readLine()) != null) {
+                str2 += str1 + "\n";
+            }
+            //log.add("write text from the golden file to the outputstream");
+            bufReader = new BufferedReader(new StringReader(str2));
+            prnWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
+            start();
+        }
+
+        public void run() {
+            try {
+                String str1 = new String();
+                while((str1 = bufReader.readLine()) != null) {
+                    prnWriter.println(str1);
+                }
+                prnWriter.close();
+                bufReader.close();
+                in.close();
+            }  catch (Exception e) {
+                log.add(e);
+                log.add("error occurs when closing the streams");
+            } finally {
+                try {
+                    socket.close();
+                }  catch (Exception e) {
+                    log.add(e);
+                    log.add("error occurs when closing the Socket");
+                }
+            }
+
+        } 
+    }
+
+    public static void main(String[] args) {
+        System.exit(new NetClient().test(args));
+    }
+
+}

Propchange: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/NetClient.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/auxiliary/Test.out
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/auxiliary/Test.out?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/auxiliary/Test.out (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/auxiliary/Test.out Fri Jun  8 09:34:52 2007
@@ -0,0 +1,37 @@
+public class Test {
+    static void createFrame() {
+	new javax.swing.JFrame();
+        System.out.println("PASSED"); 
+    } 
+    public static void main(String args[]) throws Exception { 
+        javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() { createFrame(); }});
+    } 
+} 
+public class Test {
+    static void createFrame() {
+	new javax.swing.JFrame();
+        System.out.println("PASSED"); 
+    } 
+    public static void main(String args[]) throws Exception { 
+        javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() { createFrame(); }});
+    } 
+} 
+public class Test {
+    static void createFrame() {
+	new javax.swing.JFrame();
+        System.out.println("PASSED"); 
+    } 
+    public static void main(String args[]) throws Exception { 
+        javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() { createFrame(); }});
+    } 
+} 
+public class Test {
+    static void createFrame() {
+	new javax.swing.JFrame();
+        System.out.println("PASSED"); 
+    } 
+    public static void main(String args[]) throws Exception { 
+        javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() { createFrame(); }});
+    } 
+} 
+

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/auxiliary/Test_lnx.out
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/auxiliary/Test_lnx.out?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/auxiliary/Test_lnx.out (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/net/auxiliary/Test_lnx.out Fri Jun  8 09:34:52 2007
@@ -0,0 +1,37 @@
+public class Test {
+    static void createFrame() {
+	new javax.swing.JFrame();
+        System.out.println("PASSED"); 
+    } 
+    public static void main(String args[]) throws Exception { 
+        javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() { createFrame(); }});
+    } 
+} 
+public class Test {
+    static void createFrame() {
+	new javax.swing.JFrame();
+        System.out.println("PASSED"); 
+    } 
+    public static void main(String args[]) throws Exception { 
+        javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() { createFrame(); }});
+    } 
+} 
+public class Test {
+    static void createFrame() {
+	new javax.swing.JFrame();
+        System.out.println("PASSED"); 
+    } 
+    public static void main(String args[]) throws Exception { 
+        javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() { createFrame(); }});
+    } 
+} 
+public class Test {
+    static void createFrame() {
+	new javax.swing.JFrame();
+        System.out.println("PASSED"); 
+    } 
+    public static void main(String args[]) throws Exception { 
+        javax.swing.SwingUtilities.invokeLater(new Runnable() {public void run() { createFrame(); }});
+    } 
+} 
+

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferCompactTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferCompactTest.java?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferCompactTest.java (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferCompactTest.java Fri Jun  8 09:34:52 2007
@@ -0,0 +1,127 @@
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Nikolay Bannikov
+ * @version $Revision: 1.2 $
+ */
+
+package org.apache.harmony.test.reliability.api.nio.buffers;
+
+import org.apache.harmony.test.reliability.share.Test;
+import java.nio.ByteBuffer;
+import java.util.Random;
+
+/**
+ * Goal: find resource leaks or intermittent failures caused by ByteBuffer.compact() / put() / get() / flip() operations.
+ *
+ * The test does:
+ *    1. Reads parameters, which are:
+ *          param[0] - number of iterations to call/initialize in a cycle
+ *    2. Excutes a cycle of param[0] iterations, on each iteration:
+ *        Creates byte buffer of random capacity:
+ *        For each of the byte buffer:
+ *          - fill up this buffer
+ *          - check result
+ */
+
+public class ByteBufferCompactTest extends Test {
+
+    public int callSystemGC = 1;
+
+    public int NUMBER_OF_ITERATIONS = 1000000;
+
+    final static int size = 1000;
+
+    static int cnt = 0;
+
+    public static void main(String[] args) {
+        System.exit(new ByteBufferCompactTest().test(args));
+    }
+
+    public int test(String[] params) {
+
+        parseParams(params);
+
+        ByteBuffer buf = null;
+        Random rn = new Random();
+        int allocate = 0;
+
+        for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) {
+            allocate = rn.nextInt(size);
+            buf = ByteBuffer.allocate(allocate);
+            buf.clear();
+
+            while (fillUp(buf) >= 0 || buf.position() != 0) {
+                cnt++;
+                buf.flip();
+                checkByteBuffer(buf);
+                buf.compact();
+                if (cnt > size) {
+                    break;
+                }
+            }
+
+            if (callSystemGC != 0) {
+                System.gc();
+            }
+        }
+        return pass("OK");
+    }
+
+    public void parseParams(String[] params) {
+
+        if (params.length >= 1) {
+            NUMBER_OF_ITERATIONS = Integer.parseInt(params[0]);
+        }
+
+    }
+
+    //fill up a sequence of bytes into the buffer
+    public int fillUp(ByteBuffer buf) {
+        int pos = 0;
+        int count = 0;
+        while (buf.hasRemaining() && pos < size) {
+            buf.put((byte) pos);
+            pos++;
+            count++;
+        }
+        if (pos == size && count == 0) {
+            return -1;
+        }
+        return count;
+    }
+
+    //reads a sequence of bytes from the buffer
+    public int checkByteBuffer(ByteBuffer buf) {
+        int cnt = 0;
+        byte bt = 0;
+        int bp = 0;
+        while (buf.hasRemaining()) {
+            bt = buf.get();
+            bp = buf.position() - 1;
+            if (bt != (byte) (bp)) {
+                return fail("Failed: incorrect byte in position " + bp);
+            }
+
+        }
+        return 0;
+    }
+
+
+}
+

Propchange: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferCompactTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferPutBufferTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferPutBufferTest.java?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferPutBufferTest.java (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferPutBufferTest.java Fri Jun  8 09:34:52 2007
@@ -0,0 +1,123 @@
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Nikolay Bannikov
+ * @version $Revision: 1.1 $
+ */
+
+package org.apache.harmony.test.reliability.api.nio.buffers;
+
+import org.apache.harmony.test.reliability.share.Test;
+import java.nio.ByteBuffer;
+import java.nio.IntBuffer;
+
+/**
+ * Goal: find memory leaks caused by IntBuffer.put(IntBuffer) / clear() method.
+ *
+ * The test does:
+ *    1. Reads parameters, which are:
+ *          param[0] - number of iterations a cycle
+ *          param[1] - the new buffer's capacity, in bytes  
+
+ *    2. Allocates a new byte buffer of param[1] size.
+ *    3. Allocates a new direct byte buffer of param[1] size.
+ *    4. starts a cycle of param[0] iterations. On each iteration:
+ *            - Creates a view of this byte buffer as an int buffer
+ *            - transfers direct source buffer into direct buffer
+ *            - transfers non direct source buffer into non-direct buffer
+ *            - transfers non-direct source buffer into direct buffer
+ *            - transfers direct source buffer into non-direct buffer
+ *          - runs System.gc()
+ *
+ */
+
+public class ByteBufferPutBufferTest extends Test {
+
+    public int callSystemGC = 1;
+
+    public int NUMBER_OF_ITERATIONS = 10000;
+
+    public int BUFFER_CAPACITY = 1000;
+
+    public static void main(String[] args) {
+        System.exit(new ByteBufferPutBufferTest().test(args));
+    }
+
+    public int test(String[] params) {
+
+        parseParams(params);
+
+        IntBuffer direct_buf = null;
+        IntBuffer nondirect_buf = null;
+        ByteBuffer direct_bytebuf = ByteBuffer.allocateDirect(BUFFER_CAPACITY);
+        ByteBuffer nondirect_bytebuf = ByteBuffer.allocate(BUFFER_CAPACITY);
+
+        for (int i = 0; i < NUMBER_OF_ITERATIONS; ++i) {
+
+            // if (i % 1000 == 0) {
+            //     log.add("Iteration: " + i);
+            // }
+
+            direct_buf = direct_bytebuf.asIntBuffer();
+            nondirect_buf = nondirect_bytebuf.asIntBuffer();
+
+            while (nondirect_buf.hasRemaining()) {
+                nondirect_buf.put(nondirect_buf.get()); 
+            }
+            nondirect_buf.clear();
+
+            while (direct_buf.hasRemaining()) {
+                direct_buf.put(direct_buf.get()); 
+            }
+            direct_buf.clear();
+
+            while (nondirect_buf.hasRemaining()) {
+                direct_buf.put(nondirect_buf.get()); 
+            }
+            direct_buf.clear();
+            nondirect_buf.clear();
+
+            while (direct_buf.hasRemaining()) {
+                nondirect_buf.put(direct_buf.get()); 
+            }
+
+            direct_buf.clear();
+            nondirect_buf.clear();
+
+            if (callSystemGC != 0) {
+                System.gc();
+            }
+        }
+        return pass("OK");
+    }
+
+    public void parseParams(String[] params) {
+
+        if (params.length >= 1) {
+            NUMBER_OF_ITERATIONS = Integer.parseInt(params[0]);
+        }
+
+        if (params.length >= 2) {
+            BUFFER_CAPACITY = Integer.parseInt(params[1]);
+        }
+
+    }
+
+
+}
+

Propchange: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferPutBufferTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferallocateDirectTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferallocateDirectTest.java?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferallocateDirectTest.java (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferallocateDirectTest.java Fri Jun  8 09:34:52 2007
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Nikolay Bannikov
+ * @version $Revision: 1.1 $
+ */
+
+package org.apache.harmony.test.reliability.api.nio.buffers;
+
+import org.apache.harmony.test.reliability.share.Test;
+import java.nio.ByteBuffer;
+
+/**
+ * Goal: find memory leaks caused by ByteBuffer.allocateDirect() method.
+ *
+ * The test does:
+ *    1. Reads parameters, which are:
+ *          param[0] - number of iterations to call/initialize one ByteBuffer.allocateDirect in a cycle
+ *          param[1] - the new buffer's capacity, in bytes  
+ *    2. starts a cycle of param[0] iterations. On each iteration:
+ *          - Allocates a new direct byte buffer
+ *          - runs System.gc()
+ *
+ */
+
+public class ByteBufferallocateDirectTest extends Test {
+
+    public int callSystemGC = 1;
+
+    public int NUMBER_OF_ALLOCATE_ITERATIONS = 300000;
+
+    public int BUFFER_CAPACITY = 9000;
+
+    public static void main(String[] args) {
+        System.exit(new ByteBufferallocateDirectTest().test(args));
+    }
+
+    public int test(String[] params) {
+
+        parseParams(params);
+
+        for (int i = 0; i < NUMBER_OF_ALLOCATE_ITERATIONS; ++i) {
+
+            // if (i % 10000 == 0) {
+            //    log.add("Iteration: " + i);
+            // }
+            ByteBuffer.allocateDirect(BUFFER_CAPACITY);
+
+            if (callSystemGC != 0) {
+                System.gc();
+            }
+        }
+        return pass("OK");
+    }
+
+    public void parseParams(String[] params) {
+
+        if (params.length >= 1) {
+            NUMBER_OF_ALLOCATE_ITERATIONS = Integer.parseInt(params[0]);
+        }
+
+        if (params.length >= 2) {
+            BUFFER_CAPACITY = Integer.parseInt(params[1]);
+        }
+
+    }
+
+}
+

Propchange: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferallocateDirectTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferallocateTest.java
URL: http://svn.apache.org/viewvc/harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferallocateTest.java?view=auto&rev=545554
==============================================================================
--- harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferallocateTest.java (added)
+++ harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferallocateTest.java Fri Jun  8 09:34:52 2007
@@ -0,0 +1,168 @@
+/*
+ * Copyright 2006 The Apache Software Foundation or its licensors, as applicable
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @author Nikolay Bannikov, Olessia Salmina
+ * @version $Revision: 1.1 $
+ */
+
+package org.apache.harmony.test.reliability.api.nio.buffers;
+
+
+import org.apache.harmony.test.reliability.share.Test;
+
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.charset.Charset;
+import java.nio.charset.CharsetEncoder;
+import java.nio.charset.CoderResult;
+import java.nio.charset.CodingErrorAction;
+import java.util.Random;
+import java.util.SortedMap;
+
+/**
+ * Goal: find memory leaks caused by java.nio.charset.CharsetEncoder.flush(...) method.
+ * 
+ * The test does: 
+ * 1. Reads parameters, which are: 
+ * param[0] - number of iterations to call/initialize one ByteBuffer.allocate in a cycle 
+ * param[1] - the new buffer's capacity, in bytes 
+ * 
+ * 2. Excutes a cycle of param[0] iterations, on each iteration:
+ *         a. Allocates large ByteBuffer of param[1] size. 
+ *         b. Creates a new Encoder for next available charset (obtained by Charset.availableCharsets()) 
+ *         c. Encodes a 3-char string (randomly obtained) in REPLACE mode into “large” ByteBuffer. 
+ *         d. Allocates small ByteBuffer of size 1 (byte). 
+ *         e. Calls CharsetEncoder.flush() into the small ByteBuffer. 
+ *         f. checks the results is CoderResult.OVERFLOW. 
+ *         g. Allocates another large ByteBuffer of param[1] size. 
+ *         h. Calls CharsetEncoder.flush() into the large ByteBuffer.
+ *         i. checks the results is CoderResult.OVERFLOW. 
+ *         j. Class System.gc().
+ * 
+ * 
+ */
+
+public class ByteBufferallocateTest extends Test {
+
+    public int callSystemGC = 1;
+
+    public int NUMBER_OF_ALLOCATE_ITERATIONS = 30000;
+
+    public int FIRST_BUFFER_CAPACITY = 1;
+
+    public int SECOND_BUFFER_CAPACITY = 2000;
+
+    public static void main(String[] args) {
+        System.exit(new ByteBufferallocateTest().test(args));
+    }
+
+    public int test(String[] params) {
+
+        parseParams(params);
+        SortedMap allCharsets = Charset.availableCharsets();
+        Object[] names = allCharsets.keySet().toArray();
+        // log.add("names.length: " + names.length);
+
+        for (int ChNumber = 0; ChNumber < names.length; ChNumber++) {
+            Charset charset = (Charset) allCharsets.get(names[ChNumber]);
+            
+            CharsetEncoder encoder = null;
+            CharsetEncoder encoder1 = null;
+            CharBuffer cb = null;
+            ByteBuffer bb = null;
+            ByteBuffer buf1 = null;
+            ByteBuffer buf2 = null;
+            CoderResult result = null;
+            //log.add(""+charset);
+            // log.add("names.length: " + names.length);
+            // log.add("ChNumber: " + ChNumber);
+            if(charset.isRegistered() && charset.canEncode()) {
+
+                for (int i = 0; i < NUMBER_OF_ALLOCATE_ITERATIONS; ++i) {
+                    // if (i % 1000 == 0) {
+                    //    log.add("Iteration: " + i);
+                    // }
+                
+                    String str = StringCrBuf.getRandomString((char) 3);
+                    encoder = charset.newEncoder().onMalformedInput(
+                        CodingErrorAction.REPLACE).onUnmappableCharacter(
+                        CodingErrorAction.REPLACE);
+                    cb = CharBuffer.wrap(str);
+
+                    bb = ByteBuffer.allocate(SECOND_BUFFER_CAPACITY);
+                    encoder.encode(cb, bb, true);
+
+                    buf1 = ByteBuffer.allocate(FIRST_BUFFER_CAPACITY);
+                    result = encoder.flush(buf1);
+
+                    if (result == CoderResult.OVERFLOW) {
+                        // Ignore: too smal buffer
+                    	result = null;
+                    }
+                    buf2 = ByteBuffer.allocate(SECOND_BUFFER_CAPACITY);
+                    // we intentionally call second flush(), and ignore the fact that it possible does not throw the exception,
+                    // why?  to try to cause abnormal completion.
+                    try {
+                        result = encoder.flush(buf2);                     
+                    } catch (IllegalStateException ise) {
+                        result = null;
+                    }                
+                    if (result == CoderResult.OVERFLOW) {
+                        return fail("Result shouldn't be overflow");
+                    }
+                    if (callSystemGC != 0) {
+                        System.gc();
+                    }
+                    buf1.clear();
+                    buf2.clear();
+                    bb.clear();
+                }
+            }
+        }
+        return pass("OK");
+    }
+
+    public void parseParams(String[] params) {
+
+        if (params.length >= 1) {
+            NUMBER_OF_ALLOCATE_ITERATIONS = Integer.parseInt(params[0]);
+        }
+
+        if (params.length >= 1) {
+            SECOND_BUFFER_CAPACITY = (Integer.parseInt(params[1])>20)?Integer.parseInt(params[1]):20;
+        }
+
+    }
+
+}
+
+class StringCrBuf {
+    public static String getRandomString(char size) {
+        char[] ch = new char[size];
+        Random rand = new Random();
+        int i = 0;
+        while (i < size) {
+
+            int c = rand.nextInt(0xFFFF);
+            if (Character.isJavaIdentifierPart((char) c)) {
+                ch[i++] = (char) c;
+            }
+        }
+        return new String(ch);
+    }
+}
\ No newline at end of file

Propchange: harmony/enhanced/buildtest/branches/2.0/tests/reliability/src/java/org/apache/harmony/test/reliability/api/nio/buffers/ByteBufferallocateTest.java
------------------------------------------------------------------------------
    svn:eol-style = native



Mime
View raw message