*** empty log message ***
authornavid <navid>
Wed, 11 Feb 2009 22:08:19 +0000 (22:08 +0000)
committernavid <navid>
Wed, 11 Feb 2009 22:08:19 +0000 (22:08 +0000)
22 files changed:
Robust/Transactions/dstm2/src/dstm2/benchmark/AVLTree.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/Benchmark.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/Counter.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/Counterdstm2.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/Counterdstm2Special.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/CustomBenchmark.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/CustomThread.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransaction.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransactiondstm2Special.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransactiondstm2version.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransactionv2.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/IntSetBenchmark.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/List.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/ListRelease.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/ListSnap.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/Main.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/Main_for_Book_BenchMArk.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/PureIO.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/PureIOdstm2version.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/PureIOtest.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/RBTree.java [new file with mode: 0644]
Robust/Transactions/dstm2/src/dstm2/benchmark/SkipList.java [new file with mode: 0644]

diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/AVLTree.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/AVLTree.java
new file mode 100644 (file)
index 0000000..301394b
--- /dev/null
@@ -0,0 +1,231 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import dstm2.Thread;
+import dstm2.atomic;
+import dstm2.factory.Factory;
+import java.util.Iterator;
+
+/**
+ *
+ * @author navid
+ */
+public class AVLTree extends IntSetBenchmark{
+    
+    static Factory<AvlNode> factory = Thread.makeFactory(AvlNode.class);
+        
+    protected AvlNode root;
+    
+    @atomic public interface AvlNode
+    {
+        AvlNode getLeft(); 
+        void setLeft(AvlNode value);
+     
+        AvlNode getRight();
+        void setRight(AvlNode value);
+        
+       int getHeight();    
+        void setHeight(int value);
+    
+        int getElement();
+        void setElement(int value);
+        
+    }
+        
+
+        public boolean insert( int x )
+        {
+          //  System.out.println(Thread.currentThread() + " null? " +root);
+            AVLTree.this.root = insert( x, AVLTree.this.root );
+            return true;
+        }
+
+       
+
+
+    /*    public Comparable find( Comparable x )
+        {
+            return elementAt( find( x, root ) );
+        }*/
+
+        public boolean isEmpty( )
+        {
+            return this.root == null;
+        }
+
+
+        public void printTree( )
+        {
+            if( isEmpty( ) )
+                System.out.println( "Empty tree" );
+            else
+                printTree( this.root );
+        }
+
+        private Comparable elementAt( AvlNode t )
+        {
+            return t == null ? null : t.getElement();
+        }
+
+  
+        private AvlNode insert( int x, AvlNode t )
+        {
+          //  if (root != null)
+             //   System.out.println(Thread.currentThread() + " gozo" + root.getElement());
+            
+            if( t == null ){
+              //  if (t==root)
+            //    System.out.println(Thread.currentThread() + " root? " +root);
+            //    System.out.println(Thread.currentThread() + " ff " +t);
+                t = factory.create();
+             //   System.out.println(Thread.currentThread() + " gg " +t);
+                t.setElement(x);
+                t.setLeft(null);
+                t.setRight(null);
+            }
+            
+            else if( x < t.getElement()  )
+            {
+                t.setLeft(insert( x, t.getLeft() ));
+                if( height( t.getLeft() ) - height( t.getRight() ) == 2 )
+                    if( x < t.getLeft().getElement() )
+                        t = leftRoate( t );
+                    else
+                        t = doubleLeftRotae( t );
+            }
+            else if( x > t.getElement())
+            {
+                t.setRight(insert( x, t.getRight() ));
+                if( height( t.getRight() ) - height( t.getLeft() ) == 2 )
+                    if( x > t.getRight().getElement() )
+                        t = rightRotate( t );
+                    else
+                        t = doubleRightRotate( t );
+            }
+            else;
+            
+            t.setHeight(max( height( t.getLeft() ), height( t.getRight() ) ) + 1);
+            return t;
+        }
+
+        public void makeEmpty( )
+        {
+            this.root = null;
+        }
+   
+   /*     private AvlNode find( Comparable x, AvlNode t )
+        {
+            while( t != null )
+                if( x.compareTo( t.getElement() ) < 0 )
+                    t = t.getLeft();
+                else if( x.compareTo( t.getElement() ) > 0 )
+                    t = t.getRight();
+                else
+                    return t;    // Match
+
+            return null;   // No match
+        }*/
+
+        private void printTree( AvlNode t )
+        {
+            if( t != null )
+            {
+                printTree( t.getLeft() );
+                System.out.println( t.getElement());
+                printTree( t.getRight() );
+            }
+        }
+
+       
+        private static int height( AvlNode t )
+        {
+            return t == null ? -1 : t.getHeight();
+        }
+
+
+        private static int max( int lhs, int rhs )
+        {
+            return lhs > rhs ? lhs : rhs;
+        }
+
+        private static AvlNode leftRoate( AvlNode k2 )
+        {
+          
+            AvlNode k1 = k2.getLeft();
+            k2.setLeft(k1.getRight());
+            k1.setRight(k2);
+            k2.setHeight(max( height( k2.getLeft()), height( k2.getRight() ) ) + 1);
+            k1.setHeight(max( height( k1.getLeft() ), k2.getHeight()) + 1);
+            return k1;
+        }
+
+        private static AvlNode rightRotate( AvlNode k1 )
+        {
+             
+            AvlNode k2 = k1.getRight();
+            k1.setRight(k2.getLeft());
+            k2.setLeft(k1);
+            k1.setHeight(max( height(k1.getLeft()), height( k1.getRight())) + 1);
+            
+            k2.setHeight(max( height(k2.getRight()),k1.getHeight()) + 1);
+            
+            return k2;
+        }
+
+        private static AvlNode doubleLeftRotae( AvlNode k3 )
+        {
+            k3.setLeft(rightRotate( k3.getLeft() ));
+            return leftRoate( k3 );
+        }
+
+        private static AvlNode doubleRightRotate( AvlNode k1 )
+        {
+            k1.setRight(leftRoate( k1.getRight()));
+            return rightRotate( k1 );
+        }
+
+    
+    protected void init() {
+     //   this.root = factory.create();
+
+    }
+
+    public Thread createThread(int which) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+
+  
+
+    @Override
+    public Iterator<Integer> iterator() {
+       throw new UnsupportedOperationException("Not supported yet.");
+        
+    }
+
+    @Override
+    public boolean contains(int v) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    public boolean remove(int v) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    public Thread createThread(int which, char sample, int start) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+
+
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/Benchmark.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/Benchmark.java
new file mode 100644 (file)
index 0000000..9ba48af
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Benchmark.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa
+ * Clara, California 95054, U.S.A.  All rights reserved.  
+ * 
+ * Sun Microsystems, Inc. has intellectual property rights relating to
+ * technology embodied in the product that is described in this
+ * document.  In particular, and without limitation, these
+ * intellectual property rights may include one or more of the
+ * U.S. patents listed at http://www.sun.com/patents and one or more
+ * additional patents or pending patent applications in the U.S. and
+ * in other countries.
+ * 
+ * U.S. Government Rights - Commercial software.
+ * Government users are subject to the Sun Microsystems, Inc. standard
+ * license agreement and applicable provisions of the FAR and its
+ * supplements.  Use is subject to license terms.  Sun, Sun
+ * Microsystems, the Sun logo and Java are trademarks or registered
+ * trademarks of Sun Microsystems, Inc. in the U.S. and other
+ * countries.  
+ * 
+ * This product is covered and controlled by U.S. Export Control laws
+ * and may be subject to the export or import laws in other countries.
+ * Nuclear, missile, chemical biological weapons or nuclear maritime
+ * end uses or end users, whether direct or indirect, are strictly
+ * prohibited.  Export or reexport to countries subject to
+ * U.S. embargo or to entities identified on U.S. export exclusion
+ * lists, including, but not limited to, the denied persons and
+ * specially designated nationals lists is strictly prohibited.
+ */
+
+package dstm2.benchmark;
+import dstm2.Thread;
+
+
+/**
+ * A simple interface to set up uniform benchmarks for the DSTM system
+ **/
+public interface Benchmark 
+{
+  /**
+     * Creates a thread to run the benchmark.
+     * 
+     * @param which <code>int</code> which test to run
+     * @return Thread the thread to run the benchmark
+     */
+  public Thread createThread(int which);
+  public Thread createThread(int which, char sample);
+  
+
+  /**
+   * Checks that after running the benchmark, the resulting data
+   * structure meets a specified "sanity check".  Prints messages to
+   * <code>System.out</code> if problems are found, or confirmation
+   * that no problems were found.
+   * @param stats how big should the object be?
+   */
+  public void sanityCheck();
+
+  /**
+   * Reports statistics.
+   */
+  public void report();
+}
+
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/Counter.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/Counter.java
new file mode 100644 (file)
index 0000000..728ea28
--- /dev/null
@@ -0,0 +1,416 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import dstm2.Thread;
+import dstm2.atomic;
+import dstm2.factory.Factory;
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.TransactionalFile;
+import dstm2.util.Random;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.Iterator;
+import java.util.Vector;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ *
+ * @author navid
+ */
+public class Counter extends CustomBenchmark {
+   
+    private static Factory<CountKeeper> factory = Thread.makeFactory(CountKeeper.class);
+    private CountKeeper word1_occurence;
+    private CountKeeper word2_occurence;
+    private CountKeeper word3_occurence;
+    private CountKeeper word4_occurence;
+    private CountKeeper word5_occurence;
+    private CountKeeper word6_occurence;
+    private CountKeeper word7_occurence;
+    private CountKeeper word8_occurence;
+    private CountKeeper word9_occurence;
+    private CountKeeper word10_occurence;
+    private CountKeeper word11_occurence;
+    private CountKeeper word12_occurence;
+    
+    private int[] occurences;
+    
+    
+    
+    public void init() {
+        occurences = new int[10];
+       // for (int i = 0; i< 10; i++)
+            
+            
+        word1_occurence = factory.create();
+        word1_occurence.setOccurence(0);
+              
+        word2_occurence = factory.create();
+        word2_occurence.setOccurence(0);
+              
+        word3_occurence = factory.create();
+        word3_occurence.setOccurence(0);
+              
+        word4_occurence = factory.create();
+        word4_occurence.setOccurence(0);
+              
+        word5_occurence = factory.create();
+        word5_occurence.setOccurence(0);
+              
+        word6_occurence = factory.create();
+        word6_occurence.setOccurence(0);
+              
+        word7_occurence = factory.create();
+        word7_occurence.setOccurence(0);
+              
+        word8_occurence = factory.create();
+        word8_occurence.setOccurence(0);
+              
+        word9_occurence = factory.create();
+        word9_occurence.setOccurence(0);
+              
+        word10_occurence = factory.create();
+        word10_occurence.setOccurence(0);
+        
+        word11_occurence = factory.create();
+        word11_occurence.setOccurence(0);
+        
+        word12_occurence = factory.create();
+        word12_occurence.setOccurence(0);
+        
+    }
+    
+ /*   public void execute(){
+                TransactionalFile f1 = (TransactionalFile)benchmark.m.get("2");
+                byte[] data = new byte[1];
+                char[] holder = new char[10000];
+                char[] word = new char[20];
+                boolean flag = false;    
+                long toseek = Integer.valueOf(Thread.currentThread().getName().substring(7)) * 21169; 
+                f1.seek(toseek);
+
+                data[0] ='a';
+                if (toseek != 0) //////////////// skipt the first word since its been read already
+                    while (data[0] != '\n'){
+                        int res;
+                        res = f1.read(data);
+                        if (res == -1){
+                            flag =true;
+                            break;
+                        }
+                    }
+
+                boolean completeword = false;
+           
+                int counter = 0;
+                while (f1.getFilePointer() < toseek +21169)
+                {
+                    if (flag)
+                        break;
+                    data[0] = 'a';
+                    int i = 0;
+                    int res;
+                    //if (completeparag)
+                    while ((data[0] != '\n' || completeword)){
+
+                        if (completeword){
+                           completeword = false; 
+                           int tmp = processInput(String.valueOf(word,0,counter-1)); 
+                           if (tmp != -1){
+                                switch(tmp){
+                                    case 0:
+                                        word1_occurence.setOccurence(word1_occurence.getOccurence() + 1);
+                                        break;
+                                   case 1:
+                                        word2_occurence.setOccurence(word2_occurence.getOccurence() + 1);
+                                        break;
+                                   case 2:
+                                        word3_occurence.setOccurence(word3_occurence.getOccurence() + 1);
+                                        break;
+                                   case 3:
+                                        word4_occurence.setOccurence(word4_occurence.getOccurence() + 1);
+                                        break;
+                                   case 4:
+                                        word5_occurence.setOccurence(word5_occurence.getOccurence() + 1);
+                                        break;
+                                   case 5:
+                                        word6_occurence.setOccurence(word6_occurence.getOccurence() + 1);
+                                        break;
+                                   case 6:
+                                        word7_occurence.setOccurence(word7_occurence.getOccurence() + 1);
+                                        break;
+                                   case 7:
+                                        word8_occurence.setOccurence(word8_occurence.getOccurence() + 1);
+                                        break;
+                                   case 8:
+                                        word9_occurence.setOccurence(word9_occurence.getOccurence() + 1);
+                                        break;
+                                   case 9:
+                                        word10_occurence.setOccurence(word10_occurence.getOccurence() + 1);
+                                        break;
+                                   
+                                }
+                                switch(tmp){
+                                    case 0:
+                                        occurences[0] = occurences[0] + 1;
+                                        break;
+                                   case 1:
+                                        occurences[1] = occurences[1] + 1;
+                                        break;
+                                   case 2:
+                                        occurences[2] = occurences[2] + 1;
+                                        break;
+                                   case 3:
+                                        occurences[3] = occurences[3] + 1;
+                                        break;
+                                   case 4:
+                                        occurences[4] = occurences[4] + 1;
+                                        break;
+                                   case 5:
+                                        occurences[5] = occurences[5] + 1;
+                                        break;
+                                   case 6:
+                                        occurences[6] = occurences[6] + 1;
+                                        break;
+                                   case 7:
+                                        occurences[7] = occurences[7] + 1;
+                                        break;
+                                   case 8:
+                                        occurences[8] = occurences[8] + 1;
+                                        break;
+                                   case 9:
+                                        occurences[9] = occurences[9] + 1;
+                                        break;  
+                                   }
+                                //update data structure     
+                                String tolog = new String();
+                                
+                                tolog = "-----------------------------------------------------------------";
+                                tolog += "Found Word: " + String.valueOf(word,0,counter-1) + "\nAt Offset: ";
+                                tolog += f1.getFilePointer() - counter;
+                                tolog += "\n";
+                                
+                                //byte[] towrite0 = new byte[title.length()];
+                                //towrite0  = title.getBytes();
+                                
+                                tolog += String.valueOf(holder,0,i);
+                                tolog += "\n";
+                                tolog += "-----------------------------------------------------------------";
+                                tolog += "\n";
+                                
+                                byte[] towrite = new byte[tolog.length()];
+                                towrite = tolog.getBytes();
+                                //towrite = tmpstr.getBytes();
+                                
+                                
+                                try {                   
+                                  
+                                    
+                                    ((TransactionalFile) (benchmark.m.get("3"))).write(towrite);         
+                                    //((TransactionalFile) (benchmark.m.get("3"))).write();
+
+                                } catch (IOException ex) {
+                                    Logger.getLogger(Counter.class.getName()).log(Level.SEVERE, null, ex);
+                                }
+                                
+                          } 
+                       }
+
+                       if (flag)
+                            break;
+
+                       if (completeword){
+                            holder[i] = (char)data[0];
+                            i++;
+
+                       }
+                       counter = 0;   
+                       completeword= false;
+                       data[0] = 'a';
+                       while(Character.isLetter((char)data[0]))
+                       {
+
+                            res = f1.read(data);
+                            if (res == -1){
+                                flag = true;
+                                break;
+                            }
+                            word[counter] = (char)data[0];
+                            counter++;
+                            if (counter > 1)
+                                completeword = true;
+                            holder[i] = (char)data[0];
+                            i++;
+                       }
+                    }
+                } 
+               //return true; 
+        }
+
+    
+    private int processInput(String str){
+        
+        Iterator it = benchmark.m2.keySet().iterator();
+        while (it.hasNext()){
+            Integer index = (Integer) it.next();
+            String pattern = (String)benchmark.m2.get(index);
+            if (str.equalsIgnoreCase(pattern)){
+                return index;
+            }
+        }
+        return -1;
+    }*/   
+    
+    @atomic public interface CountKeeper{
+        int getOccurence();
+        void setOccurence(int value);;
+    }
+
+    
+    public void printResults() {
+        for (int i =0; i<12; i++)
+            //System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + occurences[i]);
+             switch(i){
+                   case 0:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word1_occurence.getOccurence());
+                        break;
+                   case 1:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word2_occurence.getOccurence());
+                        break;
+                   case 2:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word3_occurence.getOccurence());
+                        break;
+                   case 3:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word4_occurence.getOccurence());
+                        break;
+                   case 4:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word5_occurence.getOccurence());
+                        break;
+                   case 5:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word6_occurence.getOccurence());
+                        break;
+                   case 6:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word7_occurence.getOccurence());
+                        break;
+                   case 7:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word8_occurence.getOccurence());
+                        break;
+                   case 8:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word9_occurence.getOccurence());
+                        break;
+                   case 9:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word10_occurence.getOccurence());
+                        break;
+                   case 10:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word11_occurence.getOccurence());
+                        break;
+                   case 11:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word12_occurence.getOccurence());
+                        break;
+             }
+        
+    
+    }
+
+    @Override
+    protected void execute(Vector arguments) {
+        String towrite = (String)arguments.get(0);
+        Integer i = (Integer)arguments.get(1);
+        int indiex_of_object = i.intValue();
+      /*  switch(indiex_of_object){
+            case 0:
+                occurences[0] = occurences[0] + 1;
+                break;
+           case 1:
+                occurences[1] = occurences[1] + 1;
+                break;
+           case 2:
+                occurences[2] = occurences[2] + 1;
+                break;
+           case 3:
+                occurences[3] = occurences[3] + 1;
+                break;
+           case 4:
+                occurences[4] = occurences[4] + 1;
+                break;
+           case 5:
+                occurences[5] = occurences[5] + 1;
+                break;
+           case 6:
+                occurences[6] = occurences[6] + 1;
+                break;
+           case 7:
+                occurences[7] = occurences[7] + 1;
+                break;
+           case 8:
+                occurences[8] = occurences[8] + 1;
+                break;
+           case 9:
+                occurences[9] = occurences[9] + 1;
+                break;  
+           }*/
+         switch(indiex_of_object){
+            case 0:
+                word1_occurence.setOccurence(word1_occurence.getOccurence() + 1);
+                break;
+           case 1:
+                word2_occurence.setOccurence(word2_occurence.getOccurence() + 1);
+                break;
+           case 2:
+                word3_occurence.setOccurence(word3_occurence.getOccurence() + 1);
+                break;
+           case 3:
+                word4_occurence.setOccurence(word4_occurence.getOccurence() + 1);
+                break;
+           case 4:
+                word5_occurence.setOccurence(word5_occurence.getOccurence() + 1);
+                break;
+           case 5:
+                word6_occurence.setOccurence(word6_occurence.getOccurence() + 1);
+                break;
+           case 6:
+                word7_occurence.setOccurence(word7_occurence.getOccurence() + 1);
+                break;
+           case 7:
+                word8_occurence.setOccurence(word8_occurence.getOccurence() + 1);
+                break;
+           case 8:
+                word9_occurence.setOccurence(word9_occurence.getOccurence() + 1);
+                break;
+           case 9:
+                word10_occurence.setOccurence(word10_occurence.getOccurence() + 1);
+                break;
+           case 10:
+                word11_occurence.setOccurence(word11_occurence.getOccurence() + 1);
+                break;
+           case 11:
+                word12_occurence.setOccurence(word12_occurence.getOccurence() + 1);
+                break;
+        }
+                         
+                                
+        try {                   
+            ((TransactionalFile) (benchmark.m.get("counteroutput"))).write(towrite.getBytes());         
+            //((TransactionalFile) (benchmark.m.get("3"))).write(towrite.getBytes());         
+            //((RandomAccessFile) (benchmark.m.get(100))).write(towrite.getBytes());
+
+        } catch (IOException ex) {
+            Logger.getLogger(Counter.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        
+    }
+
+
+    
+}
+
+
+
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/Counterdstm2.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/Counterdstm2.java
new file mode 100644 (file)
index 0000000..76cf2dd
--- /dev/null
@@ -0,0 +1,424 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import dstm2.Thread;
+import dstm2.atomic;
+import dstm2.factory.Factory;
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.TransactionalFile;
+import dstm2.util.Random;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.Iterator;
+import java.util.Vector;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ *
+ * @author navid
+ */
+public class Counterdstm2 extends CustomBenchmark {
+   
+    private static Factory<CountKeeper> factory = Thread.makeFactory(CountKeeper.class);
+    private CountKeeper word1_occurence;
+    private CountKeeper word2_occurence;
+    private CountKeeper word3_occurence;
+    private CountKeeper word4_occurence;
+    private CountKeeper word5_occurence;
+    private CountKeeper word6_occurence;
+    private CountKeeper word7_occurence;
+    private CountKeeper word8_occurence;
+    private CountKeeper word9_occurence;
+    private CountKeeper word10_occurence;
+    private CountKeeper word11_occurence;
+    private CountKeeper word12_occurence;
+    
+    private int[] occurences;
+    
+    
+    
+    public void init() {
+        occurences = new int[12];
+       // for (int i = 0; i< 10; i++)
+            
+            
+        word1_occurence = factory.create();
+        word1_occurence.setOccurence(0);
+              
+        word2_occurence = factory.create();
+        word2_occurence.setOccurence(0);
+              
+        word3_occurence = factory.create();
+        word3_occurence.setOccurence(0);
+              
+        word4_occurence = factory.create();
+        word4_occurence.setOccurence(0);
+              
+        word5_occurence = factory.create();
+        word5_occurence.setOccurence(0);
+              
+        word6_occurence = factory.create();
+        word6_occurence.setOccurence(0);
+              
+        word7_occurence = factory.create();
+        word7_occurence.setOccurence(0);
+              
+        word8_occurence = factory.create();
+        word8_occurence.setOccurence(0);
+              
+        word9_occurence = factory.create();
+        word9_occurence.setOccurence(0);
+              
+        word10_occurence = factory.create();
+        word10_occurence.setOccurence(0);
+        
+        word11_occurence = factory.create();
+        word11_occurence.setOccurence(0);
+        
+        word12_occurence = factory.create();
+        word12_occurence.setOccurence(0);
+        
+    }
+    
+ /*   public void execute(){
+                TransactionalFile f1 = (TransactionalFile)benchmark.m.get("2");
+                byte[] data = new byte[1];
+                char[] holder = new char[10000];
+                char[] word = new char[20];
+                boolean flag = false;    
+                long toseek = Integer.valueOf(Thread.currentThread().getName().substring(7)) * 21169; 
+                f1.seek(toseek);
+
+                data[0] ='a';
+                if (toseek != 0) //////////////// skipt the first word since its been read already
+                    while (data[0] != '\n'){
+                        int res;
+                        res = f1.read(data);
+                        if (res == -1){
+                            flag =true;
+                            break;
+                        }
+                    }
+
+                boolean completeword = false;
+           
+                int counter = 0;
+                while (f1.getFilePointer() < toseek +21169)
+                {
+                    if (flag)
+                        break;
+                    data[0] = 'a';
+                    int i = 0;
+                    int res;
+                    //if (completeparag)
+                    while ((data[0] != '\n' || completeword)){
+
+                        if (completeword){
+                           completeword = false; 
+                           int tmp = processInput(String.valueOf(word,0,counter-1)); 
+                           if (tmp != -1){
+                                switch(tmp){
+                                    case 0:
+                                        word1_occurence.setOccurence(word1_occurence.getOccurence() + 1);
+                                        break;
+                                   case 1:
+                                        word2_occurence.setOccurence(word2_occurence.getOccurence() + 1);
+                                        break;
+                                   case 2:
+                                        word3_occurence.setOccurence(word3_occurence.getOccurence() + 1);
+                                        break;
+                                   case 3:
+                                        word4_occurence.setOccurence(word4_occurence.getOccurence() + 1);
+                                        break;
+                                   case 4:
+                                        word5_occurence.setOccurence(word5_occurence.getOccurence() + 1);
+                                        break;
+                                   case 5:
+                                        word6_occurence.setOccurence(word6_occurence.getOccurence() + 1);
+                                        break;
+                                   case 6:
+                                        word7_occurence.setOccurence(word7_occurence.getOccurence() + 1);
+                                        break;
+                                   case 7:
+                                        word8_occurence.setOccurence(word8_occurence.getOccurence() + 1);
+                                        break;
+                                   case 8:
+                                        word9_occurence.setOccurence(word9_occurence.getOccurence() + 1);
+                                        break;
+                                   case 9:
+                                        word10_occurence.setOccurence(word10_occurence.getOccurence() + 1);
+                                        break;
+                                   
+                                }
+                                switch(tmp){
+                                    case 0:
+                                        occurences[0] = occurences[0] + 1;
+                                        break;
+                                   case 1:
+                                        occurences[1] = occurences[1] + 1;
+                                        break;
+                                   case 2:
+                                        occurences[2] = occurences[2] + 1;
+                                        break;
+                                   case 3:
+                                        occurences[3] = occurences[3] + 1;
+                                        break;
+                                   case 4:
+                                        occurences[4] = occurences[4] + 1;
+                                        break;
+                                   case 5:
+                                        occurences[5] = occurences[5] + 1;
+                                        break;
+                                   case 6:
+                                        occurences[6] = occurences[6] + 1;
+                                        break;
+                                   case 7:
+                                        occurences[7] = occurences[7] + 1;
+                                        break;
+                                   case 8:
+                                        occurences[8] = occurences[8] + 1;
+                                        break;
+                                   case 9:
+                                        occurences[9] = occurences[9] + 1;
+                                        break;  
+                                   }
+                                //update data structure     
+                                String tolog = new String();
+                                
+                                tolog = "-----------------------------------------------------------------";
+                                tolog += "Found Word: " + String.valueOf(word,0,counter-1) + "\nAt Offset: ";
+                                tolog += f1.getFilePointer() - counter;
+                                tolog += "\n";
+                                
+                                //byte[] towrite0 = new byte[title.length()];
+                                //towrite0  = title.getBytes();
+                                
+                                tolog += String.valueOf(holder,0,i);
+                                tolog += "\n";
+                                tolog += "-----------------------------------------------------------------";
+                                tolog += "\n";
+                                
+                                byte[] towrite = new byte[tolog.length()];
+                                towrite = tolog.getBytes();
+                                //towrite = tmpstr.getBytes();
+                                
+                                
+                                try {                   
+                                  
+                                    
+                                    ((TransactionalFile) (benchmark.m.get("3"))).write(towrite);         
+                                    //((TransactionalFile) (benchmark.m.get("3"))).write();
+
+                                } catch (IOException ex) {
+                                    Logger.getLogger(Counter.class.getName()).log(Level.SEVERE, null, ex);
+                                }
+                                
+                          } 
+                       }
+
+                       if (flag)
+                            break;
+
+                       if (completeword){
+                            holder[i] = (char)data[0];
+                            i++;
+
+                       }
+                       counter = 0;   
+                       completeword= false;
+                       data[0] = 'a';
+                       while(Character.isLetter((char)data[0]))
+                       {
+
+                            res = f1.read(data);
+                            if (res == -1){
+                                flag = true;
+                                break;
+                            }
+                            word[counter] = (char)data[0];
+                            counter++;
+                            if (counter > 1)
+                                completeword = true;
+                            holder[i] = (char)data[0];
+                            i++;
+                       }
+                    }
+                } 
+               //return true; 
+        }
+
+    
+    private int processInput(String str){
+        
+        Iterator it = benchmark.m2.keySet().iterator();
+        while (it.hasNext()){
+            Integer index = (Integer) it.next();
+            String pattern = (String)benchmark.m2.get(index);
+            if (str.equalsIgnoreCase(pattern)){
+                return index;
+            }
+        }
+        return -1;
+    }*/   
+    
+    @atomic public interface CountKeeper{
+        int getOccurence();
+        void setOccurence(int value);;
+    }
+
+    
+    public void printResults() {
+        for (int i =0; i<10; i++)
+            //System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + occurences[i]);
+             switch(i){
+                   case 0:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word1_occurence.getOccurence());
+                        break;
+                   case 1:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word2_occurence.getOccurence());
+                        break;
+                   case 2:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word3_occurence.getOccurence());
+                        break;
+                   case 3:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word4_occurence.getOccurence());
+                        break;
+                   case 4:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word5_occurence.getOccurence());
+                        break;
+                   case 5:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word6_occurence.getOccurence());
+                        break;
+                   case 6:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word7_occurence.getOccurence());
+                        break;
+                   case 7:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word8_occurence.getOccurence());
+                        break;
+                   case 8:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word9_occurence.getOccurence());
+                        break;
+                   case 9:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word10_occurence.getOccurence());
+                        break;
+                   case 10:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word11_occurence.getOccurence());
+                        break;
+                   case 11:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word12_occurence.getOccurence());
+                        break;
+                        
+             }
+        
+    
+    }
+
+    @Override
+    protected void execute(Vector arguments) {
+        String towrite = (String)arguments.get(0);
+        Integer i = (Integer)arguments.get(1);
+        int indiex_of_object = i.intValue();
+       /* switch(indiex_of_object){
+            case 0:
+                occurences[0] = occurences[0] + 1;
+                break;
+           case 1:
+                occurences[1] = occurences[1] + 1;
+                break;
+           case 2:
+                occurences[2] = occurences[2] + 1;
+                break;
+           case 3:
+                occurences[3] = occurences[3] + 1;
+                break;
+           case 4:
+                occurences[4] = occurences[4] + 1;
+                break;
+           case 5:
+                occurences[5] = occurences[5] + 1;
+                break;
+           case 6:
+                occurences[6] = occurences[6] + 1;
+                break;
+           case 7:
+                occurences[7] = occurences[7] + 1;
+                break;
+           case 8:
+                occurences[8] = occurences[8] + 1;
+                break;
+           case 9:
+                occurences[9] = occurences[9] + 1;
+                break;  
+           case 10:
+                occurences[10] = occurences[10] + 1;
+                break; 
+           case 11:
+                occurences[11] = occurences[11] + 1;
+                break; 
+           }*/
+         switch(indiex_of_object){
+            case 0:
+                word1_occurence.setOccurence(word1_occurence.getOccurence() + 1);
+                break;
+           case 1:
+                word2_occurence.setOccurence(word2_occurence.getOccurence() + 1);
+                break;
+           case 2:
+                word3_occurence.setOccurence(word3_occurence.getOccurence() + 1);
+                break;
+           case 3:
+                word4_occurence.setOccurence(word4_occurence.getOccurence() + 1);
+                break;
+           case 4:
+                word5_occurence.setOccurence(word5_occurence.getOccurence() + 1);
+                break;
+           case 5:
+                word6_occurence.setOccurence(word6_occurence.getOccurence() + 1);
+                break;
+           case 6:
+                word7_occurence.setOccurence(word7_occurence.getOccurence() + 1);
+                break;
+           case 7:
+                word8_occurence.setOccurence(word8_occurence.getOccurence() + 1);
+                break;
+           case 8:
+                word9_occurence.setOccurence(word9_occurence.getOccurence() + 1);
+                break;
+           case 9:
+                word10_occurence.setOccurence(word10_occurence.getOccurence() + 1);
+                break;
+           case 10:
+                word11_occurence.setOccurence(word11_occurence.getOccurence() + 1);
+                break;
+           case 11:
+                word12_occurence.setOccurence(word12_occurence.getOccurence() + 1);
+                break;
+        }
+                         
+                                
+        try {                   
+            
+            //((TransactionalFile) (benchmark.m.get("3"))).write(towrite.getBytes());         
+            //((RandomAccessFile) (benchmark.m.get(100))).write(towrite.getBytes());
+            ((RandomAccessFile) (benchmark.m.get("counterdstm2output"))).write(towrite.getBytes());
+
+        } catch (IOException ex) {
+            Logger.getLogger(Counter.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        
+    }
+
+
+    
+}
+
+
+
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/Counterdstm2Special.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/Counterdstm2Special.java
new file mode 100644 (file)
index 0000000..aa70ec5
--- /dev/null
@@ -0,0 +1,430 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import dstm2.Thread;
+import dstm2.atomic;
+import dstm2.factory.Factory;
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.TransactionalFile;
+import dstm2.SpecialTransactionalFile;
+import dstm2.util.Random;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.Iterator;
+import java.util.Vector;
+import java.util.concurrent.locks.ReentrantLock;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ *
+ * @author navid
+ */
+public class Counterdstm2Special extends CustomBenchmark {
+   
+    private static Factory<CountKeeper> factory = Thread.makeFactory(CountKeeper.class);
+    private CountKeeper word1_occurence;
+    private CountKeeper word2_occurence;
+    private CountKeeper word3_occurence;
+    private CountKeeper word4_occurence;
+    private CountKeeper word5_occurence;
+    private CountKeeper word6_occurence;
+    private CountKeeper word7_occurence;
+    private CountKeeper word8_occurence;
+    private CountKeeper word9_occurence;
+    private CountKeeper word10_occurence;
+    private CountKeeper word11_occurence;
+    private CountKeeper word12_occurence;
+    
+    private int[] occurences;
+    
+    
+    
+    public void init() {
+        try {
+            benchmark.m.put("counterdstm2specialoutput", new SpecialTransactionalFile("/scratch/TransactionalIO/WordCunterBenchmarkFiles/counter_benchmark_output.text", "rw"));
+            occurences = new int[12];
+            // for (int i = 0; i< 10; i++)
+
+            word1_occurence = factory.create();
+            word1_occurence.setOccurence(0);
+
+            word2_occurence = factory.create();
+            word2_occurence.setOccurence(0);
+
+            word3_occurence = factory.create();
+            word3_occurence.setOccurence(0);
+
+            word4_occurence = factory.create();
+            word4_occurence.setOccurence(0);
+
+            word5_occurence = factory.create();
+            word5_occurence.setOccurence(0);
+
+            word6_occurence = factory.create();
+            word6_occurence.setOccurence(0);
+
+            word7_occurence = factory.create();
+            word7_occurence.setOccurence(0);
+
+            word8_occurence = factory.create();
+            word8_occurence.setOccurence(0);
+
+            word9_occurence = factory.create();
+            word9_occurence.setOccurence(0);
+
+            word10_occurence = factory.create();
+            word10_occurence.setOccurence(0);
+
+            word11_occurence = factory.create();
+            word11_occurence.setOccurence(0);
+
+            word12_occurence = factory.create();
+            word12_occurence.setOccurence(0);
+        } catch (FileNotFoundException ex) {
+            Logger.getLogger(Counterdstm2Special.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        
+    }
+    
+ /*   public void execute(){
+                TransactionalFile f1 = (TransactionalFile)benchmark.m.get("2");
+                byte[] data = new byte[1];
+                char[] holder = new char[10000];
+                char[] word = new char[20];
+                boolean flag = false;    
+                long toseek = Integer.valueOf(Thread.currentThread().getName().substring(7)) * 21169; 
+                f1.seek(toseek);
+
+                data[0] ='a';
+                if (toseek != 0) //////////////// skipt the first word since its been read already
+                    while (data[0] != '\n'){
+                        int res;
+                        res = f1.read(data);
+                        if (res == -1){
+                            flag =true;
+                            break;
+                        }
+                    }
+
+                boolean completeword = false;
+           
+                int counter = 0;
+                while (f1.getFilePointer() < toseek +21169)
+                {
+                    if (flag)
+                        break;
+                    data[0] = 'a';
+                    int i = 0;
+                    int res;
+                    //if (completeparag)
+                    while ((data[0] != '\n' || completeword)){
+
+                        if (completeword){
+                           completeword = false; 
+                           int tmp = processInput(String.valueOf(word,0,counter-1)); 
+                           if (tmp != -1){
+                                switch(tmp){
+                                    case 0:
+                                        word1_occurence.setOccurence(word1_occurence.getOccurence() + 1);
+                                        break;
+                                   case 1:
+                                        word2_occurence.setOccurence(word2_occurence.getOccurence() + 1);
+                                        break;
+                                   case 2:
+                                        word3_occurence.setOccurence(word3_occurence.getOccurence() + 1);
+                                        break;
+                                   case 3:
+                                        word4_occurence.setOccurence(word4_occurence.getOccurence() + 1);
+                                        break;
+                                   case 4:
+                                        word5_occurence.setOccurence(word5_occurence.getOccurence() + 1);
+                                        break;
+                                   case 5:
+                                        word6_occurence.setOccurence(word6_occurence.getOccurence() + 1);
+                                        break;
+                                   case 6:
+                                        word7_occurence.setOccurence(word7_occurence.getOccurence() + 1);
+                                        break;
+                                   case 7:
+                                        word8_occurence.setOccurence(word8_occurence.getOccurence() + 1);
+                                        break;
+                                   case 8:
+                                        word9_occurence.setOccurence(word9_occurence.getOccurence() + 1);
+                                        break;
+                                   case 9:
+                                        word10_occurence.setOccurence(word10_occurence.getOccurence() + 1);
+                                        break;
+                                   
+                                }
+                                switch(tmp){
+                                    case 0:
+                                        occurences[0] = occurences[0] + 1;
+                                        break;
+                                   case 1:
+                                        occurences[1] = occurences[1] + 1;
+                                        break;
+                                   case 2:
+                                        occurences[2] = occurences[2] + 1;
+                                        break;
+                                   case 3:
+                                        occurences[3] = occurences[3] + 1;
+                                        break;
+                                   case 4:
+                                        occurences[4] = occurences[4] + 1;
+                                        break;
+                                   case 5:
+                                        occurences[5] = occurences[5] + 1;
+                                        break;
+                                   case 6:
+                                        occurences[6] = occurences[6] + 1;
+                                        break;
+                                   case 7:
+                                        occurences[7] = occurences[7] + 1;
+                                        break;
+                                   case 8:
+                                        occurences[8] = occurences[8] + 1;
+                                        break;
+                                   case 9:
+                                        occurences[9] = occurences[9] + 1;
+                                        break;  
+                                   }
+                                //update data structure     
+                                String tolog = new String();
+                                
+                                tolog = "-----------------------------------------------------------------";
+                                tolog += "Found Word: " + String.valueOf(word,0,counter-1) + "\nAt Offset: ";
+                                tolog += f1.getFilePointer() - counter;
+                                tolog += "\n";
+                                
+                                //byte[] towrite0 = new byte[title.length()];
+                                //towrite0  = title.getBytes();
+                                
+                                tolog += String.valueOf(holder,0,i);
+                                tolog += "\n";
+                                tolog += "-----------------------------------------------------------------";
+                                tolog += "\n";
+                                
+                                byte[] towrite = new byte[tolog.length()];
+                                towrite = tolog.getBytes();
+                                //towrite = tmpstr.getBytes();
+                                
+                                
+                                try {                   
+                                  
+                                    
+                                    ((TransactionalFile) (benchmark.m.get("3"))).write(towrite);         
+                                    //((TransactionalFile) (benchmark.m.get("3"))).write();
+
+                                } catch (IOException ex) {
+                                    Logger.getLogger(Counter.class.getName()).log(Level.SEVERE, null, ex);
+                                }
+                                
+                          } 
+                       }
+
+                       if (flag)
+                            break;
+
+                       if (completeword){
+                            holder[i] = (char)data[0];
+                            i++;
+
+                       }
+                       counter = 0;   
+                       completeword= false;
+                       data[0] = 'a';
+                       while(Character.isLetter((char)data[0]))
+                       {
+
+                            res = f1.read(data);
+                            if (res == -1){
+                                flag = true;
+                                break;
+                            }
+                            word[counter] = (char)data[0];
+                            counter++;
+                            if (counter > 1)
+                                completeword = true;
+                            holder[i] = (char)data[0];
+                            i++;
+                       }
+                    }
+                } 
+               //return true; 
+        }
+
+    
+    private int processInput(String str){
+        
+        Iterator it = benchmark.m2.keySet().iterator();
+        while (it.hasNext()){
+            Integer index = (Integer) it.next();
+            String pattern = (String)benchmark.m2.get(index);
+            if (str.equalsIgnoreCase(pattern)){
+                return index;
+            }
+        }
+        return -1;
+    }*/   
+    
+    @atomic public interface CountKeeper{
+        int getOccurence();
+        void setOccurence(int value);;
+    }
+
+    
+    public void printResults() {
+        for (int i =0; i<10; i++)
+            //System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + occurences[i]);
+             switch(i){
+                   case 0:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word1_occurence.getOccurence());
+                        break;
+                   case 1:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word2_occurence.getOccurence());
+                        break;
+                   case 2:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word3_occurence.getOccurence());
+                        break;
+                   case 3:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word4_occurence.getOccurence());
+                        break;
+                   case 4:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word5_occurence.getOccurence());
+                        break;
+                   case 5:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word6_occurence.getOccurence());
+                        break;
+                   case 6:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word7_occurence.getOccurence());
+                        break;
+                   case 7:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word8_occurence.getOccurence());
+                        break;
+                   case 8:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word9_occurence.getOccurence());
+                        break;
+                   case 9:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word10_occurence.getOccurence());
+                        break;
+                   case 10:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word11_occurence.getOccurence());
+                        break;
+                   case 11:
+                        System.out.println((String)benchmark.m2.get(Integer.valueOf(i)) + " " + word12_occurence.getOccurence());
+                        break;
+                        
+             }
+        
+    
+    }
+
+    @Override
+    protected void execute(Vector arguments) {
+        String towrite = (String)arguments.get(0);
+        Integer i = (Integer)arguments.get(1);
+        int indiex_of_object = i.intValue();
+       /* switch(indiex_of_object){
+            case 0:
+                occurences[0] = occurences[0] + 1;
+                break;
+           case 1:
+                occurences[1] = occurences[1] + 1;
+                break;
+           case 2:
+                occurences[2] = occurences[2] + 1;
+                break;
+           case 3:
+                occurences[3] = occurences[3] + 1;
+                break;
+           case 4:
+                occurences[4] = occurences[4] + 1;
+                break;
+           case 5:
+                occurences[5] = occurences[5] + 1;
+                break;
+           case 6:
+                occurences[6] = occurences[6] + 1;
+                break;
+           case 7:
+                occurences[7] = occurences[7] + 1;
+                break;
+           case 8:
+                occurences[8] = occurences[8] + 1;
+                break;
+           case 9:
+                occurences[9] = occurences[9] + 1;
+                break;  
+           case 10:
+                occurences[10] = occurences[10] + 1;
+                break; 
+           case 11:
+                occurences[11] = occurences[11] + 1;
+                break; 
+           }*/
+         switch(indiex_of_object){
+            case 0:
+                word1_occurence.setOccurence(word1_occurence.getOccurence() + 1);
+                break;
+           case 1:
+                word2_occurence.setOccurence(word2_occurence.getOccurence() + 1);
+                break;
+           case 2:
+                word3_occurence.setOccurence(word3_occurence.getOccurence() + 1);
+                break;
+           case 3:
+                word4_occurence.setOccurence(word4_occurence.getOccurence() + 1);
+                break;
+           case 4:
+                word5_occurence.setOccurence(word5_occurence.getOccurence() + 1);
+                break;
+           case 5:
+                word6_occurence.setOccurence(word6_occurence.getOccurence() + 1);
+                break;
+           case 6:
+                word7_occurence.setOccurence(word7_occurence.getOccurence() + 1);
+                break;
+           case 7:
+                word8_occurence.setOccurence(word8_occurence.getOccurence() + 1);
+                break;
+           case 8:
+                word9_occurence.setOccurence(word9_occurence.getOccurence() + 1);
+                break;
+           case 9:
+                word10_occurence.setOccurence(word10_occurence.getOccurence() + 1);
+                break;
+           case 10:
+                word11_occurence.setOccurence(word11_occurence.getOccurence() + 1);
+                break;
+           case 11:
+                word12_occurence.setOccurence(word12_occurence.getOccurence() + 1);
+                break;
+        }
+                         
+                                
+        try {                   
+            
+            //((TransactionalFile) (benchmark.m.get("3"))).write(towrite.getBytes());         
+            //((RandomAccessFile) (benchmark.m.get(100))).write(towrite.getBytes());
+            ((SpecialTransactionalFile) (benchmark.m.get("counterdstm2specialoutput"))).write(towrite.getBytes());
+
+        } catch (IOException ex) {
+            Logger.getLogger(Counter.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        
+    }
+
+
+    
+}
+
+
+
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/CustomBenchmark.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/CustomBenchmark.java
new file mode 100644 (file)
index 0000000..7b02b6d
--- /dev/null
@@ -0,0 +1,113 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.TransactionalFile;
+import TransactionalIO.exceptions.GracefulException;
+import dstm2.atomic;
+import dstm2.benchmark.Counter.CountKeeper;
+import dstm2.factory.Factory;
+import dstm2.Thread;
+import dstm2.util.Random;
+import java.util.Vector;
+import java.util.concurrent.Callable;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ *
+ * @author navid
+ */
+public abstract class CustomBenchmark{
+    
+ public ReentrantLock programlock = new ReentrantLock();
+
+   public static final Object lock = new Object();
+  /**
+   * local variable
+   */
+   int element;
+  /**
+   * local variable
+   */
+   int value;
+
+  /**
+   * Number of calls to insert()
+   */
+   int insertCalls = 0;
+  /**
+   * number of calls to contains()
+   */
+   int containsCalls = 0;
+  /**
+   * number of calls to remove()
+   */
+   int removeCalls = 0;
+  /**
+   * amount by which the set size has changed
+   */
+   int delta = 0;
+   protected abstract void init();
+   
+   protected abstract void execute(Vector arguments);
+   
+   protected abstract void printResults();
+    
+   public CustomBenchmark() {
+     init();
+   }
+   // public static Vector hotwords;
+
+
+  
+  /**
+   * Prints an error message to <code>System.out</code>, including a
+   *  standard header to identify the message as an error message.
+   * @param s String describing error
+   */
+  protected static void reportError(String s) {
+    System.out.println(" ERROR: " + s);
+    System.out.flush();
+  }
+  
+  public void report() {
+    System.out.println("Insert/Remove calls:\t" + (insertCalls + removeCalls));
+    System.out.println("Contains calls:\t" + containsCalls);
+  }
+
+    
+
+  
+  public void sanityCheck() {
+    long expected =  delta;
+    int length = 1;
+    
+    int prevValue = Integer.MIN_VALUE;
+  /*  for (int value : this) {
+      length++;
+      if (value < prevValue) {
+        System.out.println("ERROR: set  not sorted");
+        System.exit(0);
+      }
+      if (value == prevValue) {
+        System.out.println("ERROR: set has duplicates!");
+        System.exit(0);
+      }
+      if (length == expected) {
+        System.out.println("ERROR: set has bad length!");
+        System.exit(0);
+      }
+     
+    }*/
+    System.out.println("Integer Set OK");
+  }
+  
+
+
+
+ }
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/CustomThread.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/CustomThread.java
new file mode 100644 (file)
index 0000000..67519f1
--- /dev/null
@@ -0,0 +1,1100 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package dstm2.benchmark;
+
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.TransactionalFile;
+import TransactionalIO.exceptions.GracefulException;
+import com.sun.corba.se.impl.protocol.SpecialMethod;
+import dstm2.SpecialTransactionalFile;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import dstm2.Thread;
+import dstm2.atomic;
+import dstm2.factory.Factory;
+import java.io.RandomAccessFile;
+import java.util.Vector;
+import java.util.concurrent.Callable;
+
+/**
+ *
+ * @author navid
+ */
+public class CustomThread implements Runnable {
+
+
+    private Thread thread;
+    private CustomBenchmark mybenchmark;
+    static final Object lock = new Object();
+    int insertCalls = 0;
+    /**
+     * number of calls to contains()
+     */
+    int containsCalls = 0;
+    /**
+     * number of calls to remove()
+     */
+    int removeCalls = 0;
+    /**
+     * amount by which the set size has changed
+     */
+    int delta = 0;
+    Object[] locksforfiles;
+
+    public CustomThread(CustomBenchmark benchmark) {
+        locksforfiles = new Object[26];
+        for (int i = 0; i < 26; i++) {
+            locksforfiles[i] = new Object();
+        }
+        mybenchmark = benchmark;
+        thread = new Thread(this);
+
+    }
+
+    public void start() {
+        thread.start();
+    }
+
+    public void join() {
+        try {
+            thread.join();
+        } catch (InterruptedException ex) {
+            Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+        }
+    }
+
+    public void run() {
+        if (mybenchmark instanceof Counter) {
+            counterBenchmark();
+        } else if (mybenchmark instanceof Counterdstm2) {
+            counterdstm2Benchmark();
+        } else if (mybenchmark instanceof Counterdstm2Special) {
+            counterdstm2SpecialBenchmark();
+        } else if (mybenchmark instanceof FinancialTransaction) {
+            financialBenchmark();
+        } else if (mybenchmark instanceof FinancialTransactionv2) {
+            financialBenchmarkv2();
+        } else if (mybenchmark instanceof FinancialTransactiondstm2Special) {
+            financialBenchmarkdstm2Special();
+        } else if (mybenchmark instanceof PureIO) {
+            pureIOBenchmark();
+        } else if (mybenchmark instanceof PureIOdstm2version) {
+            pureIOdstm2Benchmark();
+        }
+    }
+
+    public void pureIOBenchmark() {
+        try {
+            //try {
+            // TransactionalFile f1 = (TransactionalFile)benchmark.m.get("0");
+            //TransactionalFile f1 = new TransactionalFile("/scratch/TransactionalIO/PureIOBenchmarkFiles/randomwords.text", "rw");
+            //RandomAccessFile f1 = new RandomAccessFile("/home/navid/randomwords.text", "rw");
+            TransactionalFile f1 = new TransactionalFile("/scratch/TransactionalIO/PureIOBenchmarkFiles/randomwords.text", "rw");
+
+            byte[] b = new byte[20];
+            byte[] data = new byte[1];
+            char[] holder = new char[40];
+
+            boolean flag = false;
+            int res = 0;
+            long toseek;
+            long threadoffset;
+            ///for two thread
+            threadoffset = 204485;
+            //for four thread
+            //threadoffset = 204485/2;
+            //for eight thread
+            //threadoffset = 204485/4;
+
+            toseek = (Integer.valueOf(Thread.currentThread().getName().substring(7))) * threadoffset;
+            f1.seek(toseek);
+            //   System.out.println(toseek + " " + Thread.currentThread());
+
+            data[0] = 'a';
+            if (toseek != 0) {
+                //////////////// skipt the first word since its been read already
+                while (data[0] != '\n') {
+                    f1.read(data);
+                }
+            }
+            while (f1.getFilePointer() < toseek + threadoffset) {
+
+                if (flag == true) {
+                    break;
+                }
+                try {
+                    data[0] = 'a';
+                    int i = 0;
+                    int result = 0;
+                    while (data[0] != '\n') {
+                        result = f1.read(data);
+                        if (result == -1) {
+                            flag = true;
+                            break;
+                        //return;
+                        }
+
+
+                        holder[i] = (char) data[0];
+                        //   synchronized(benchmark.lock){
+                        //    System.out.println(Thread.currentThread() + " " + holder[i]);
+                        // }
+                        i++;
+                    }
+                    if (holder[0] == '\n') {
+                        continue;
+                    }
+                    byte[] towrite = new byte[String.valueOf(holder, 0, i).length()];
+                    towrite = String.valueOf(holder, 0, i).getBytes();
+                    //final Vector arguments = new Vector();
+
+                    //arguments.add(holder);
+                    //arguments.add(Integer.valueOf(i));
+                    //arguments.add(towrite);
+                    //String.copyValueOf(word, 0, counter - 1)
+                    //boolean resultt = Thread.doIt(new Callable<Boolean>() {
+                    //mybenchmark.programlock.lock();
+                    // public Boolean call() {
+                    // System.out.println(holder[0]);
+                    // System.out.println((int)Character.toLowerCase(holder[0])-97);
+                    ((TransactionalFile) (benchmark.m.get(String.valueOf(holder, 0, i).toLowerCase().substring(0, 1)))).write(towrite);
+                //         mybenchmark.execute(arguments);
+                //return true;
+                // }
+                //mybenchmark.programlock.unlock();
+                //});
+                // arguments.clear();
+                } catch (GracefulException g) {
+                    //           synchronized (lock) {
+                    //             mybenchmark.printResults();
+                    /*insertCalls   += myInsertCalls;
+                    removeCalls   += myRemoveCalls;
+                    containsCalls += myContainsCalls;
+                    delta         += myDelta;*/
+                    //           }
+                }
+            }
+        //    } catch (IOException ex) {
+        //        Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+        //   }
+        } catch (IOException ex) {
+            Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+        }
+    //    } catch (IOException ex) {
+    //        Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+    //   }
+
+
+    }
+
+    public void pureIOdstm2Benchmark() {
+        try {
+            //try {
+            // TransactionalFile f1 = (TransactionalFile)benchmark.m.get("0");
+            //TransactionalFile f1 = new TransactionalFile("/scratch/TransactionalIO/PureIOBenchmarkFiles/randomwords.text", "rw");
+            RandomAccessFile f1 = new RandomAccessFile("/scratch/TransactionalIO/PureIOBenchmarkFiles/randomwords.text", "rw");
+            //TransactionalFile f1 = new TransactionalFile("/home/navid/randomwords.text", "rw");
+
+            byte[] b = new byte[20];
+            byte[] data = new byte[1];
+            char[] holder = new char[40];
+
+            boolean flag = false;
+            int res = 0;
+            long toseek;
+            long threadoffset;
+            ///for two thread
+            //threadoffset = 204485;
+            //for four thread
+            //threadoffset = 204485/2;
+            //for eight thread
+            threadoffset = 204485/4;
+
+            toseek = (Integer.valueOf(Thread.currentThread().getName().substring(7))) * threadoffset;
+            f1.seek(toseek);
+            //   System.out.println(toseek + " " + Thread.currentThread());
+
+            data[0] = 'a';
+            if (toseek != 0) {
+                //////////////// skipt the first word since its been read already
+                while (data[0] != '\n') {
+                    f1.read(data);
+                }
+            }
+            while (f1.getFilePointer() < toseek + threadoffset) {
+
+                if (flag == true) {
+                    break;
+                }
+                try {
+                    data[0] = 'a';
+                    int i = 0;
+                    int result = 0;
+                    while (data[0] != '\n') {
+                        result = f1.read(data);
+                        if (result == -1) {
+                            flag = true;
+                            break;
+                        //return;
+                        }
+
+
+                        holder[i] = (char) data[0];
+                        //   synchronized(benchmark.lock){
+                        //    System.out.println(Thread.currentThread() + " " + holder[i]);
+                        // }
+                        i++;
+                    }
+                    if (holder[0] == '\n') {
+                        continue;
+                    }
+                    byte[] towrite = new byte[String.valueOf(holder, 0, i).length()];
+                    towrite = String.valueOf(holder, 0, i).getBytes();
+                    //synchronized (locksforfiles[(int) Character.toLowerCase(holder[0]) - 97]) {
+                    final Vector arguments = new Vector();
+
+                    arguments.add(holder);
+                    arguments.add(Integer.valueOf(i));
+                    arguments.add(towrite);
+                    
+                    boolean resultt = Thread.doIt(new Callable<Boolean>() {
+                    //mybenchmark.programlock.lock();
+                        public Boolean call() {
+                    // System.out.println(holder[0]);
+                    // System.out.println((int)Character.toLowerCase(holder[0])-97);
+                    
+                         mybenchmark.execute(arguments);
+                        return true;
+                        }
+                        
+                    });
+
+                    arguments.clear();
+                } catch (GracefulException g) {
+                    //           synchronized (lock) {
+                    //             mybenchmark.printResults();
+                    /*insertCalls   += myInsertCalls;
+                    removeCalls   += myRemoveCalls;
+                    containsCalls += myContainsCalls;
+                    delta         += myDelta;*/
+                    //           }
+                }
+            }
+
+        } catch (IOException ex) {
+            Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+        }
+
+
+    }
+
+    public void financialBenchmark() {
+        try {
+            //       try {
+            //RandomAccessFile f1 = new RandomAccessFile("/home/navid/financialtransaction.text", "rw");
+            RandomAccessFile f1 = new RandomAccessFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/financialtransaction.text", "rw");
+            //TransactionalFile f1 = new TransactionalFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/financialtransaction.text", "rw");
+            byte[] data = new byte[1];
+    
+            char[] word = new char[20];
+
+            boolean flag = false;
+            int counter = 0;
+            long toseek;
+            long threadoffset;
+            ///for two thread
+            threadoffset = 360611;
+            //for four thread
+            //threadoffset = 360611/2;
+            //for eight thread
+            //threadoffset = 360611/4;
+
+            toseek = (Integer.valueOf(Thread.currentThread().getName().substring(7))) * threadoffset; //;// 53417;266914;//// ;
+
+            f1.seek(toseek);
+            // System.out.println(toseek);
+
+            data[0] = 'a';
+            if (toseek != 0) {
+                //////////////// skipt the first word since its been read already
+                while (data[0] != '\n') {
+                    int res;
+                    res = f1.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                }
+            }
+
+
+            while (f1.getFilePointer() < toseek + threadoffset) {
+                if (flag) {
+                    break;
+                }
+                final Vector arguments = new Vector();
+                try {
+                    counter = 0;
+                    data[0] = 'a';
+                    while (data[0] != ' ') {
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+                        word[counter] = (char) data[0];
+                        counter++;
+                    }
+
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(String.copyValueOf(word, 0, counter - 1));
+                    counter = 0;
+                    data[0] = 'a';
+                    while (data[0] != ' ') {
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+                        word[counter] = (char) data[0];
+                        counter++;
+
+                    }
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(Integer.parseInt(String.valueOf(word, 0, counter - 1)));
+
+                    counter = 0;
+                    data[0] = 'a';
+
+                    while (data[0] != ' ') {
+
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+                        word[counter] = (char) data[0];
+                        counter++;
+                    }
+
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(String.copyValueOf(word, 0, counter - 1));
+
+
+                    counter = 0;
+                    data[0] = 'a';
+
+                    while (data[0] != '\n') {
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+
+                        word[counter] = (char) data[0];
+                        counter++;
+                    }
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(String.copyValueOf(word, 0, counter - 1));
+                    //  mybenchmark.programlock.lock();
+                    boolean result = Thread.doIt(new Callable<Boolean>() {
+                        public Boolean call() {
+
+                            try {
+
+                                mybenchmark.execute(arguments);
+                            } catch (java.lang.ArrayIndexOutOfBoundsException e) {
+                                e.printStackTrace();
+                            }
+                            return true;
+                        }
+                    });
+                    //  mybenchmark.programlock.unlock();
+                    arguments.clear();
+                } catch (GracefulException g) {
+                }
+            }
+           // mybenchmark.printResults();
+        } catch (IOException ex) {
+            Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+        }
+
+    }
+
+    public void financialBenchmarkv2() {
+        try {
+            //       try {
+            RandomAccessFile f1 = new RandomAccessFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/financialtransaction.text", "rw");
+            //TransactionalFile f1 = new TransactionalFile("/home/navid/financialtransaction.text", "rw");
+            byte[] data = new byte[1];
+
+            char[] word = new char[20];
+
+            boolean flag = false;
+            int counter = 0;
+            long toseek;
+            long threadoffset;
+            ///for two thread
+            threadoffset = 360611;
+            //for four thread
+            //threadoffset = 360611/2;
+            //for eight thread
+            //threadoffset = 360611/4;
+
+            toseek = (Integer.valueOf(Thread.currentThread().getName().substring(7))) * threadoffset; //;// 53417;266914;//// ;
+
+            f1.seek(toseek);
+            // System.out.println(toseek);
+
+            data[0] = 'a';
+            if (toseek != 0) {
+                //////////////// skipt the first word since its been read already
+                while (data[0] != '\n') {
+                    int res;
+                    res = f1.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                }
+            }
+
+
+            while (f1.getFilePointer() < toseek + threadoffset) {
+                if (flag) {
+                    break;
+                }
+                final Vector arguments = new Vector();
+                try {
+                    counter = 0;
+                    data[0] = 'a';
+                    while (data[0] != ' ') {
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+                        word[counter] = (char) data[0];
+                        counter++;
+                    }
+
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(String.copyValueOf(word, 0, counter - 1));
+                    counter = 0;
+                    data[0] = 'a';
+                    while (data[0] != ' ') {
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+                        word[counter] = (char) data[0];
+                        counter++;
+                    }
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(Integer.parseInt(String.valueOf(word, 0, counter - 1)));
+
+                    counter = 0;
+                    data[0] = 'a';
+
+                    while (data[0] != ' ') {
+
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+                        word[counter] = (char) data[0];
+                        counter++;
+
+                    }
+
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(String.copyValueOf(word, 0, counter - 1));
+
+
+                    counter = 0;
+                    data[0] = 'a';
+
+                    while (data[0] != '\n') {
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+
+                        word[counter] = (char) data[0];
+                        counter++;
+                    }
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(String.copyValueOf(word, 0, counter - 1));
+                    
+                   // mybenchmark.programlock.lock();
+                    final TransactionalFile file = new  TransactionalFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/accountbalance.text", "rw");
+                    arguments.add(file);
+                    boolean result = Thread.doIt(new Callable<Boolean>() {
+
+                        public Boolean call() {
+
+                            try {
+
+                                mybenchmark.execute(arguments);
+                            } catch (java.lang.ArrayIndexOutOfBoundsException e) {
+                                e.printStackTrace();
+                            }
+
+                            return true;
+                        }
+                    });
+                    //mybenchmark.programlock.unlock();
+                    arguments.clear();
+                    file.file.close();
+                } catch (GracefulException g) {
+                }
+            }
+            //mybenchmark.printResults();
+//        } catch (IOException ex) {
+//            Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+        //     }
+        } catch (IOException ex) {
+            Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+        }
+//        } catch (IOException ex) {
+//            Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+    //     }
+
+
+
+    }
+
+    public void financialBenchmarkdstm2Special() {
+        try {
+            //       try {
+            RandomAccessFile f1 = new RandomAccessFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/financialtransaction.text", "rw");
+            //TransactionalFile f1 = new TransactionalFile("/home/navid/financialtransaction.text", "rw");
+            byte[] data = new byte[1];
+            char[] word = new char[20];
+            boolean flag = false;
+            int counter = 0;
+            long toseek;
+            long threadoffset;
+            ///for two thread
+            //threadoffset = 360611;
+            //for four thread
+            //threadoffset = 360611/2;
+            //for eight thread
+            threadoffset = 360611/4;
+            //threadoffset = 360611/8;
+
+            toseek = (Integer.valueOf(Thread.currentThread().getName().substring(7))) * threadoffset; //;// 53417;266914;//// ;
+
+            f1.seek(toseek);
+            // System.out.println(toseek);
+
+            data[0] = 'a';
+            if (toseek != 0) {
+                //////////////// skipt the first word since its been read already
+                while (data[0] != '\n') {
+                    int res;
+                    res = f1.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                }
+            }
+
+
+            while (f1.getFilePointer() < toseek + threadoffset) {
+                if (flag) {
+                    break;
+                }
+                final Vector arguments = new Vector();
+                try {
+                    counter = 0;
+                    data[0] = 'a';
+                    while (data[0] != ' ') {
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+                        word[counter] = (char) data[0];
+                        counter++;
+                    }
+
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(String.copyValueOf(word, 0, counter - 1));
+                    counter = 0;
+                    data[0] = 'a';
+                    while (data[0] != ' ') {
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+                        word[counter] = (char) data[0];
+                        counter++;
+                    }
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(Integer.parseInt(String.valueOf(word, 0, counter - 1)));
+
+                    counter = 0;
+                    data[0] = 'a';
+
+                    while (data[0] != ' ') {
+
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+                        word[counter] = (char) data[0];
+                        counter++;
+                    }
+
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(String.copyValueOf(word, 0, counter - 1));
+
+
+                    counter = 0;
+                    data[0] = 'a';
+
+                    while (data[0] != '\n') {
+                        int res = f1.read(data);
+                        if (res == -1) {
+                            flag = true;
+                            break;
+                        }
+
+                        word[counter] = (char) data[0];
+                        counter++;
+                    }
+                    if (flag) {
+                        return;
+                    }
+                    arguments.add(String.copyValueOf(word, 0, counter - 1));
+                    //mybenchmark.programlock.lock();
+                    final SpecialTransactionalFile file = new  SpecialTransactionalFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/accountbalance.text", "rw");
+                    arguments.add(file);
+                    boolean result = Thread.doIt(new Callable<Boolean>() {
+
+                        public Boolean call() {
+
+                            try {
+
+                                mybenchmark.execute(arguments);
+                            } catch (java.lang.ArrayIndexOutOfBoundsException e) {
+                                e.printStackTrace();
+                            }
+
+                            return true;
+                        }
+                    });
+                    //mybenchmark.programlock.unlock();
+                    file.close();
+                    arguments.clear();
+                } catch (GracefulException g) {
+                }
+            }
+         //mybenchmark.printResults();
+        } catch (IOException ex) {
+            Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+        }
+    }
+
+    public void counterBenchmark() {
+        try {
+
+
+            //TransactionalFile f1 = new TransactionalFile("/scratch/TransactionalIO/WordCunterBenchmarkFiles/iliad.text", "rw");
+            //TransactionalFile f1 = new TransactionalFile("/scratch/TransactionalIO/WordCunterBenchmarkFiles/iliad.text", "rw");
+            RandomAccessFile f1 = new RandomAccessFile("/scratch/TransactionalIO/WordCunterBenchmarkFiles/iliad.text", "rw");
+            //RandomAccessFile f1 = new RandomAccessFile("/home/navid/iliad.text", "rw");
+            byte[] data = new byte[1];
+            char[] holder = new char[10000];
+            char[] word = new char[20];
+            boolean flag = false;
+            long toseek;
+            long threadoffset;
+            ///for two thread
+            //threadoffset = 211686;
+            //for four thread
+            threadoffset = 211686/4;
+            //for eight thread
+            //threadoffset = 211686/4;
+            // System.out.print("dddd");
+            toseek = Integer.valueOf(Thread.currentThread().getName().substring(7)) * threadoffset;//42337;
+
+            f1.seek(toseek);
+
+            data[0] = 'a';
+            if (toseek != 0) {
+                //////////////// skipt the first word since its been read already
+                while (data[0] != '\n') {
+                    int res;
+                    res = f1.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                }
+            }
+            boolean completeword = false;
+
+            int counter = 0;
+
+            while (f1.getFilePointer() < toseek + threadoffset) {
+                try {
+                    if (flag) {
+                        break;
+                    }
+                    data[0] = 'a';
+                    int i = 0;
+                    int res;
+                    //if (completeparag)
+                    while (data[0] != '\n' || completeword) {
+
+                        if (completeword) {
+                            completeword = false;
+                            final int tmp = processInput(String.valueOf(word, 0, counter - 1));
+                            if (tmp != -1) {
+                                final String topass = execute(holder, word, counter, i, f1.getFilePointer());
+                                boolean result;
+                                final Vector arguments = new Vector();
+                                arguments.add(topass);
+                                arguments.add(Integer.valueOf(tmp));
+                                result = Thread.doIt(new Callable<Boolean>() {
+
+                                    public Boolean call() {
+                                        // mybenchmark.programlock.lock();
+                                        //mybenchmark.execute(topass, tmp);
+                                        mybenchmark.execute(arguments);
+                                        // mybenchmark.programlock.unlock();
+                                        return true;
+                                    }
+                                });
+                                arguments.clear();
+                            }
+                        }
+
+                        if (flag) {
+                            break;
+                        }
+                        if (completeword) {
+                            holder[i] = (char) data[0];
+                            i++;
+                        }
+                        counter = 0;
+                        completeword = false;
+                        data[0] = 'a';
+                        while (Character.isLetter((char) data[0])) {
+
+                            res = f1.read(data);
+                            if (res == -1) {
+                                flag = true;
+                                break;
+                            }
+                            word[counter] = (char) data[0];
+                            counter++;
+                            if (counter > 1) {
+                                completeword = true;
+                            }
+                            holder[i] = (char) data[0];
+                            i++;
+                        }
+                    }
+                } catch (GracefulException g) {
+                }
+            }
+
+        //mybenchmark.printResults();
+        } catch (IOException ex) {
+            Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+        }
+
+    }
+
+    public void counterdstm2Benchmark() {
+        try {
+
+
+            //TransactionalFile f1 = new TransactionalFile("/scratch/TransactionalIO/WordCunterBenchmarkFiles/iliad.text", "rw");
+            //  TransactionalFile f1 = new TransactionalFile("/home/navid/iliad.text", "rw");
+            RandomAccessFile f1 = new RandomAccessFile("/scratch/TransactionalIO/WordCunterBenchmarkFiles/iliad.text", "rw");
+            byte[] data = new byte[1];
+            char[] holder = new char[10000];
+            char[] word = new char[20];
+            boolean flag = false;
+            long threadoffset;
+            long toseek;
+            // threadoffset = 211686;
+            //for four thread
+            //threadoffset = 211686/2;
+            //for eight thread
+            threadoffset = 211686 / 4;
+            // System.out.print("dddd");
+            toseek = Integer.valueOf(Thread.currentThread().getName().substring(7)) * threadoffset;
+            f1.seek(toseek);
+
+            data[0] = 'a';
+            if (toseek != 0) {
+                //////////////// skipt the first word since its been read already
+                while (data[0] != '\n') {
+                    int res;
+                    res = f1.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                }
+            }
+            boolean completeword = false;
+
+            int counter = 0;
+
+            while (f1.getFilePointer() < toseek + threadoffset) {
+                try {
+                    if (flag) {
+                        break;
+                    }
+                    data[0] = 'a';
+                    int i = 0;
+                    int res;
+                    //if (completeparag)
+                    while (data[0] != '\n' || completeword) {
+
+                        if (completeword) {
+                            completeword = false;
+                            final int tmp = processInput(String.valueOf(word, 0, counter - 1));
+                            if (tmp != -1) {
+                                final String topass = execute(holder, word, counter, i, f1.getFilePointer());
+                                boolean result;
+                                final Vector arguments = new Vector();
+                                arguments.add(topass);
+                                arguments.add(Integer.valueOf(tmp));
+                                mybenchmark.programlock.lock();
+                                result = Thread.doIt(new Callable<Boolean>() {
+
+                                    public Boolean call() {
+                                        mybenchmark.execute(arguments);
+                                        return true;
+                                    }
+                                });
+                                mybenchmark.programlock.unlock();
+                                arguments.clear();
+                            }
+                        }
+
+                        if (flag) {
+                            break;
+                        }
+                        if (completeword) {
+                            holder[i] = (char) data[0];
+                            i++;
+                        }
+                        counter = 0;
+                        completeword = false;
+                        data[0] = 'a';
+                        while (Character.isLetter((char) data[0])) {
+
+                            res = f1.read(data);
+                            if (res == -1) {
+                                flag = true;
+                                break;
+                            }
+                            word[counter] = (char) data[0];
+                            counter++;
+                            if (counter > 1) {
+                                completeword = true;
+                            }
+                            holder[i] = (char) data[0];
+                            i++;
+                        }
+                    }
+                } catch (GracefulException g) {
+                }
+            }
+        } catch (IOException ex) {
+            Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+        }
+
+    }
+
+    public void counterdstm2SpecialBenchmark() {
+        try {
+
+
+            //TransactionalFile f1 = new TransactionalFile("/scratch/TransactionalIO/WordCunterBenchmarkFiles/iliad.text", "rw");
+            //  TransactionalFile f1 = new TransactionalFile("/home/navid/iliad.text", "rw");
+            RandomAccessFile f1 = new RandomAccessFile("/scratch/TransactionalIO/WordCunterBenchmarkFiles/iliad.text", "rw");
+            byte[] data = new byte[1];
+            char[] holder = new char[10000];
+            char[] word = new char[20];
+            boolean flag = false;
+            long threadoffset;
+            long toseek;
+            //threadoffset = 211686;
+            //for four thread
+            threadoffset = 211686/2;
+            //for eight thread
+            //threadoffset = 211686/4;
+            // System.out.print("dddd");
+            toseek = Integer.valueOf(Thread.currentThread().getName().substring(7)) * threadoffset;
+            f1.seek(toseek);
+
+            data[0] = 'a';
+            if (toseek != 0) {
+                //////////////// skipt the first word since its been read already
+                while (data[0] != '\n') {
+                    int res;
+                    res = f1.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                }
+            }
+            boolean completeword = false;
+
+            int counter = 0;
+
+            while (f1.getFilePointer() < toseek + threadoffset) {
+                try {
+                    if (flag) {
+                        break;
+                    }
+                    data[0] = 'a';
+                    int i = 0;
+                    int res;
+                    //if (completeparag)
+                    while (data[0] != '\n' || completeword) {
+
+                        if (completeword) {
+                            completeword = false;
+                            final int tmp = processInput(String.valueOf(word, 0, counter - 1));
+                            if (tmp != -1) {
+                                final String topass = execute(holder, word, counter, i, f1.getFilePointer());
+                                boolean result;
+                                final Vector arguments = new Vector();
+                                arguments.add(topass);
+                                arguments.add(Integer.valueOf(tmp));
+                                //   mybenchmark.programlock.lock();
+                                result = Thread.doIt(new Callable<Boolean>() {
+
+                                    public Boolean call() {
+                                        mybenchmark.execute(arguments);
+                                        return true;
+                                    }
+                                });
+                                //  mybenchmark.programlock.unlock();
+                                arguments.clear();
+                            }
+                        }
+
+                        if (flag) {
+                            break;
+                        }
+                        if (completeword) {
+                            holder[i] = (char) data[0];
+                            i++;
+                        }
+                        counter = 0;
+                        completeword = false;
+                        data[0] = 'a';
+                        while (Character.isLetter((char) data[0])) {
+
+                            res = f1.read(data);
+                            if (res == -1) {
+                                flag = true;
+                                break;
+                            }
+                            word[counter] = (char) data[0];
+                            counter++;
+                            if (counter > 1) {
+                                completeword = true;
+                            }
+                            holder[i] = (char) data[0];
+                            i++;
+                        }
+                    }
+                } catch (GracefulException g) {
+                }
+            }
+        } catch (IOException ex) {
+            Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+        }
+    }
+
+    private int processInput(String str) {
+
+        Iterator it = benchmark.m2.keySet().iterator();
+        while (it.hasNext()) {
+            Integer index = (Integer) it.next();
+            String pattern = (String) benchmark.m2.get(index);
+            if (str.equalsIgnoreCase(pattern)) {
+                return index;
+            }
+        }
+        return -1;
+    }
+
+    private String execute(char[] holder, char[] word, int counter, int i, long offset) {
+        String tolog = new String();
+
+        tolog = "-----------------------------------------------------------------";
+        tolog += "Found Word: " + String.valueOf(word, 0, counter - 1) + "\nAt Offset: ";
+        tolog += offset - counter;
+        tolog += "\n";
+
+        //byte[] towrite0 = new byte[title.length()];
+        //towrite0  = title.getBytes();
+
+        tolog += String.valueOf(holder, 0, i);
+        tolog += "\n";
+        tolog += "-----------------------------------------------------------------";
+        tolog += "\n";
+
+        byte[] towrite = new byte[tolog.length()];
+        towrite = tolog.getBytes();
+        //towrite = tmpstr.getBytes();
+
+        return tolog;
+    /*try {                   
+    //  System.out.println("dddddd");
+    
+    ((TransactionalFile) (benchmark.m.get("3"))).write(towrite);         
+    //((TransactionalFile) (benchmark.m.get("3"))).write();
+    
+    } catch (IOException ex) {
+    Logger.getLogger(CustomThread.class.getName()).log(Level.SEVERE, null, ex);
+    }*/
+    }
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransaction.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransaction.java
new file mode 100644 (file)
index 0000000..54f2bff
--- /dev/null
@@ -0,0 +1,574 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.Defaults;
+import TransactionalIO.core.TransactionalFile;
+import dstm2.AtomicArray;
+import dstm2.atomic;
+import dstm2.Thread;
+import dstm2.factory.Factory;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.Vector;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+
+/**
+ *
+ * @author navid
+ */
+public class FinancialTransaction extends CustomBenchmark{
+     TransactionalFile file;
+     TransactionalFile file2;
+     private static Factory<FinancialTransactionDS> factory = Thread.makeFactory(FinancialTransactionDS.class);
+     private static Factory<RootHolder> factory2 = Thread.makeFactory(RootHolder.class);
+     private static Factory<FTrHolder> factory3 = Thread.makeFactory(FTrHolder.class);
+     
+     LockedFTrHolder[] hlm;
+     
+     
+ /*    String buyer1 = new String();
+     int soldshare1 = 0;
+     String seller1 = new String();
+     
+     String buyer2 = new String();
+     int soldshare2 = 0;
+     String seller2 = new String();
+     
+     String buyer3 = new String();
+     int soldshare3 = 0;
+     String seller3 = new String();
+     
+     String buyer4 = new String();
+     int soldshare4 = 0;
+     String seller4 = new String();
+     
+     String buyer5 = new String();
+     int soldshare5 = 0;
+     String seller5 = new String();
+     
+     int lockedcounter = 1;*/
+     AtomicArray<FTrHolder> financialTransactionKeeper;
+
+    protected void init() {
+       // hlm = new LockedFTrHolder[20];
+      /*  for (int i=0; i<20; i++){
+            hlm[i] = new LockedFTrHolder();
+            hlm[i].counter =1;
+            hlm[i].lk = new LockedFinancialTransactionDS[5];
+            for (int j=0; j<5; j++){
+                hlm[i].lk[j] = new LockedFinancialTransactionDS();
+                hlm[i].lk[j].buyer = "";
+                hlm[i].lk[j].seller = "";
+                hlm[i].lk[j].soldshare = 0;
+            }
+                
+        }*/
+        
+        
+        file = new  TransactionalFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/accountbalance.text", "rw");
+        file2 = new TransactionalFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/financialtransactionlog.text", "rw");
+        
+        RootHolder ck =  factory2.create();
+        ck.setFinancialTransactionKeeper(new AtomicArray<FTrHolder>(FTrHolder.class, 20));
+        
+
+        financialTransactionKeeper = ck.getFinancialTransactionKeeper();
+        for (int i=0; i<20; i++){ 
+           
+            FTrHolder f1 = factory3.create();
+            f1.setCounter(1);
+            f1.setFinancialTransactionKeeper(new AtomicArray<FinancialTransactionDS>(FinancialTransactionDS.class, 5));
+            for (int j=0; j<5; j++)
+            {
+                FinancialTransactionDS ftk = factory.create();
+                ftk.setBuyer("");
+                ftk.setSeller("");
+                ftk.setSoldShare(0);
+                AtomicArray<FinancialTransactionDS> tmp = f1.getFinancialTransactionKeeper();
+                tmp.set(j, ftk);
+            }
+          
+            
+            financialTransactionKeeper.set(i, f1);
+       }
+    }
+
+
+    protected void execute(Vector arguments) {
+        try {
+
+            //TransactionalFile file = (TransactionalFile) benchmark.m.get("5");
+            
+           // TransactionalFile file = (TransactionalFile) benchmark.m.get("accountbalance");
+        //    RandomAccessFile file = (RandomAccessFile) benchmark.m.get("7");
+            String oldowner = (String) arguments.get(0);
+            Integer stocktrade = (Integer) arguments.get(1);
+            String newowner = (String) arguments.get(2);
+            String nameofstock = (String) arguments.get(3);
+            Integer offset1 = (Integer) benchmark.m4.get(oldowner);
+            Integer offset2 = (Integer) benchmark.m4.get(newowner);
+        
+      
+            file.seek(offset1 * Defaults.FILEFRAGMENTSIZE);
+            Vector v = computeandupdate(true, stocktrade, nameofstock);
+            String st = (String)(v.get(1));
+            long offset1towrite = ((Long)(v.get(0))).longValue();
+            
+            file.seek(offset2 * Defaults.FILEFRAGMENTSIZE);
+            v = computeandupdate(false, stocktrade, nameofstock);
+            String st2 = (String)(v.get(1));
+            long offset2towrite = ((Long)(v.get(0))).longValue();
+            
+            
+            file.seek(offset1towrite);
+            file.write(st.getBytes());
+            file.seek(offset2towrite);
+            file.write(st2.getBytes());
+            
+            String towrite = oldowner + " " + stocktrade.toString() + " " + newowner + " " + nameofstock + " processed\n";
+            file2.write(towrite.getBytes());
+            
+               int i; 
+               for (i=0;i<benchmark.stocks.length; i++){
+                   if (benchmark.stocks[i].equalsIgnoreCase(nameofstock))
+                       break;
+               }
+                switch(financialTransactionKeeper.get(i).getCounter()){
+                case 1:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(2);
+                      break;
+                case 2:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(3);
+                      break;
+                case 3:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(4);
+                      break;
+                case 4:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(5);
+                      break;
+                case 5:    
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(1);
+                      break;
+            }
+            
+        } catch (IOException ex) {
+            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        }
+
+
+   /* private Vector computeandupdate(boolean type, Integer stocktrade, String origstockname ){
+        try {
+            // try{
+            //    RandomAccessFile file = (RandomAccessFile) benchmark.m.get("7");
+            //TransactionalFile file = (TransactionalFile) benchmark.m.get("5");
+        //    TransactionalFile file = (TransactionalFile) benchmark.m.get("accountbalance");
+            Vector v = new Vector();
+            byte[] data = new byte[1];
+            char[] balance = new char[20];
+
+            // int counter =0;
+            boolean flag = false;
+            data[0] = 'a';
+            int counter = 0;
+            while (data[0] != '\n') {
+                try {
+                    int res;
+                    res = file.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                } catch (IOException ex) {
+                    Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+
+            while (true) {
+                try {
+                    char[] stname = new char[10];
+                    data[0] = 'a';
+                    int ol = 0;
+                    while (data[0] != ' ') {
+                        try {
+                            int res;
+                            res = file.read(data);
+                            if (res == -1) {
+                                flag = true;
+                                break;
+                            }
+                            stname[ol] = (char) data[0];
+                            ol++;
+                        } catch (IOException ex) {
+                            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                        }
+                    }
+                    String stockname = String.copyValueOf(stname, 0, ol - 1);
+                    if (stockname.equalsIgnoreCase(origstockname)) {
+                        break;
+                    } else {
+                        while (data[0] != '\n') {
+                            file.read(data);
+                        }
+                    }
+                } catch (IOException ex) {
+                    Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+
+
+
+
+            data[0] = 'a';
+            while ((char) data[0] != ':') {
+                try {
+                    int res;
+                    res = file.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                } catch (IOException ex) {
+                    Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+            int res = file.read(data);
+            long offsetofnumber = file.getFilePointer();
+            do {
+                res = file.read(data);
+                if (res == -1) {
+                    flag = true;
+                    break;
+                }
+                balance[counter] = (char) data[0];
+                counter++;
+            } while (Character.isDigit((char) data[0]) || (char) data[0] == '-');
+
+            int oldbalance = Integer.parseInt(String.valueOf(balance, 0, counter - 1));
+
+            //    return oldnumber;
+
+            int newnumber;
+            if (type) {
+                newnumber = oldbalance - stocktrade.intValue();
+            } else {
+                newnumber = oldbalance + stocktrade.intValue();
+
+
+                //////   file.seek(offsetofnumber);
+            }
+            String st = new String();
+            st = String.valueOf(newnumber);
+            if (String.valueOf(newnumber).length() < counter - 1) {
+
+                for (int i = 0; i < counter - String.valueOf(newnumber).length(); i++) {
+                    st += (new String(" "));
+                }
+            }
+
+            v.add(Long.valueOf(offsetofnumber));
+            v.add(st);
+            return v;
+
+        } catch (IOException ex) {
+            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+            return null;
+        }
+
+    }*/
+    
+     private Vector computeandupdate(boolean type, Integer stocktrade, String origstockname ){
+        try {
+            // try{
+            //    RandomAccessFile file = (RandomAccessFile) benchmark.m.get("7");
+            //TransactionalFile file = (TransactionalFile) benchmark.m.get("5");
+        //    TransactionalFile file = (TransactionalFile) benchmark.m.get("accountbalance");
+            Vector v = new Vector();
+            byte[] data = new byte[11];
+            char[] balance = new char[20];
+
+            int counter =0;
+            file.read(data);
+            
+            int adad; 
+            for (adad=0;adad<benchmark.stocks.length; adad++){
+                if (benchmark.stocks[adad].equalsIgnoreCase(origstockname))
+                    break;
+            }
+            file.skipBytes(adad*41);
+            
+            data = new byte[41];
+            file.read(data);
+            int i =0;
+            while (true) {
+                    i = 0;
+                    char[] stname = new char[10];
+                    int ol = 0;
+                   // System.out.println("char " + (char)data[i]);
+                    while (data[i] != ' ') {
+                            stname[ol] = (char) data[i];
+                         //   System.out.println(ol);
+                            ol++;
+                            i++;
+                     
+                    }
+                   
+                    String stockname = String.copyValueOf(stname, 0, ol);
+                    if (stockname.equalsIgnoreCase(origstockname)) {
+                        break;
+                    }
+                    else{ 
+                      //  file.read(data);
+                        System.out.println("WTF??!!");
+                    }
+            }
+
+
+
+
+
+            while ((char) data[i] != ':') {
+                 i++;
+            }
+
+            i++;
+            long offsetofnumber = file.getFilePointer();
+            offsetofnumber += i-40;
+       
+            do {
+                //System.out.println("d " + (char) data[i]);
+                i++;
+                balance[counter] = (char) data[i];
+                counter++;
+            } while (Character.isDigit((char) data[i]) || (char) data[i] == '-');
+
+            int oldbalance = Integer.parseInt(String.valueOf(balance, 0, counter - 1));
+
+            //    return oldnumber;
+
+            int newnumber;
+            if (type) {
+                newnumber = oldbalance - stocktrade.intValue();
+            } else {
+                newnumber = oldbalance + stocktrade.intValue();
+
+
+                //////   file.seek(offsetofnumber);
+            }
+            String st = new String();
+            st = String.valueOf(newnumber);
+            if (String.valueOf(newnumber).length() < counter - 1) {
+
+                for (int j = 0; j < counter - String.valueOf(newnumber).length(); j++) {
+                    st += (new String(" "));
+                }
+            }
+
+            v.add(Long.valueOf(offsetofnumber));
+            v.add(st);
+            return v;
+
+        } catch (IOException ex) {
+            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+            return null;
+        }
+
+    }
+
+    protected  void printResults() {
+      
+     for (int i=0; i<20; i++){   
+        System.out.println("----------------------------------------------");  
+        System.out.println(benchmark.stocks[i]);  
+        for (int j=0; j<5; j++)
+        {
+            System.out.print(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getSeller() + " ");
+            System.out.print(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getBuyer() + " ");
+            System.out.println(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getSoldShare());
+        }
+        System.out.println("----------------------------------------------");
+      }
+    /*    for (int i=0; i<20; i++){ 
+            System.out.println("----------------------------------------------");  
+            System.out.println(benchmark.stocks[i]);  
+            for (int j=0; j<5; j++)
+            {
+                 
+                System.out.print(hlm[i].lk[j].seller + " ");
+                System.out.print(hlm[i].lk[j].buyer + " ");
+                System.out.println(hlm[i].lk[j].soldshare);
+            }
+            System.out.println("----------------------------------------------");
+        }*/
+        
+      /*  System.out.print(finance1.getSeller() + " ");
+        System.out.print(finance1.getBuyer() + " ");
+        System.out.println(finance1.getSoldShare());
+        
+        System.out.print(finance2.getSeller() + " ");
+        System.out.print(finance2.getBuyer()+ " ");
+        System.out.println(finance2.getSoldShare());
+        
+        System.out.print(finance3.getSeller() + " ");
+        System.out.print(finance3.getBuyer()+ " ");
+        System.out.println(finance3.getSoldShare());
+        
+        System.out.print(finance4.getSeller() + " ");
+        System.out.print(finance4.getBuyer()+ " ");
+        System.out.println(finance4.getSoldShare());
+        
+        System.out.print(finance5.getSeller() + " ");
+        System.out.print(finance5.getBuyer()+ " ");
+        System.out.println(finance5.getSoldShare());*/
+      
+        /*System.out.print(buyer1 + " ");
+        System.out.print(soldshare1 + " ");
+        System.out.println(seller1);
+        
+        System.out.print(buyer2 + " ");
+        System.out.print(soldshare2 + " ");
+        System.out.println(seller2);
+        
+        System.out.print(buyer3 + " ");
+        System.out.print(soldshare3 + " ");
+        System.out.println(seller3);
+        
+        System.out.print(buyer4 + " ");
+        System.out.print(soldshare4 + " ");
+        System.out.println(seller4);
+        
+        System.out.print(buyer5 + " ");
+        System.out.print(soldshare5 + " ");
+        System.out.println(seller5);*/
+        
+        //System.out.println("----------------------------------------------");
+    }
+    
+
+    
+    
+      @atomic public interface FinancialTransactionDS{
+        String getSeller();
+        void setSeller(String value);
+        int getSoldShare();
+        void setSoldShare(int value);
+        String getBuyer();
+        void setBuyer(String value);  
+      }
+      
+      @atomic public interface FTrHolder{
+          AtomicArray<FinancialTransactionDS> getFinancialTransactionKeeper();
+          void setFinancialTransactionKeeper(AtomicArray<FinancialTransactionDS> arr);
+          int getCounter();
+          void setCounter(int value);
+      }
+      
+      @atomic public interface RootHolder{
+          AtomicArray<FTrHolder> getFinancialTransactionKeeper();
+          void setFinancialTransactionKeeper(AtomicArray<FTrHolder> arr);
+        //  int getCounter();
+        //  void setCounter(int value);
+      }
+      
+      class LockedFinancialTransactionDS{
+          public String seller;
+          public String buyer;
+          public int soldshare;          
+      }
+      
+      class LockedFTrHolder{
+          public LockedFinancialTransactionDS[] lk = new LockedFinancialTransactionDS[5];
+          public int counter;
+      }
+      
+      
+      
+      
+      /*    private int getOldBalance(){
+         
+         byte[] data = new byte[1];
+         char[] balance = new char[20];
+         
+        // int counter =0;
+         boolean flag = false;
+         data[0] = 'a';
+         counter = 0;
+         while (data[0] != '\n') {
+                int res;
+                res = file.read(data);
+                if (res == -1) {
+                    flag = true;
+                    break;
+                }
+            }
+        while ((char) data[0] != ':') {
+            int res;
+            res = file.read(data);
+            if (res == -1) {
+                flag = true;
+                break;
+            }
+        }
+        int res = file.read(data);
+        offsetofnumber = file.getFilePointer();
+        do {
+            res = file.read(data);
+            if (res == -1) {
+                flag = true;
+                break;
+            }
+            balance[counter] = (char) data[0];
+            counter++;
+        } while (Character.isDigit((char) data[0]) || (char)data[0] == '-');
+     //   System.out.println((char)data[0]);
+            int oldnumber = Integer.parseInt(String.valueOf(balance, 0, counter - 1));
+       //     System.out.println(oldnumber);
+            return oldnumber;
+            
+
+    }
+    
+    private void updateFile(int newnumber){
+        try {
+            
+            file.seek(offsetofnumber);
+         //   System.out.println(String.valueOf(newnumber));
+            file.write(String.valueOf(newnumber).getBytes());
+            if (String.valueOf(newnumber).length() < counter - 1){
+             
+                for (int i=0; i<counter-String.valueOf(newnumber).length(); i++){
+                  
+                    file.write((new String(" ")).getBytes());
+                }
+            }
+            file.write((new String("\n")).getBytes());
+   
+            } catch (IOException ex) {
+                Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+            }
+    }*/
+
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransactiondstm2Special.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransactiondstm2Special.java
new file mode 100644 (file)
index 0000000..6145e61
--- /dev/null
@@ -0,0 +1,313 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package dstm2.benchmark;
+
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.Defaults;
+import dstm2.AtomicArray;
+import dstm2.SpecialTransactionalFile;
+import dstm2.atomic;
+import dstm2.Thread;
+import dstm2.factory.Factory;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.Vector;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ *
+ * @author navid
+ */
+public class FinancialTransactiondstm2Special extends CustomBenchmark {
+
+    //private SpecialTransactionalFile file;
+   // private SpecialTransactionalFile file2;
+    private static Factory<FinancialTransactionDS> factory = Thread.makeFactory(FinancialTransactionDS.class);
+    private static Factory<RootHolder> factory2 = Thread.makeFactory(RootHolder.class);
+    private static Factory<FTrHolder> factory3 = Thread.makeFactory(FTrHolder.class);
+    AtomicArray<FTrHolder> financialTransactionKeeper;
+
+    protected void init() {
+       // try {
+            
+            //file = new SpecialTransactionalFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/accountbalance.text", "rw");
+            //file2 = new SpecialTransactionalFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/financialtransactionlog.text", "rw");
+
+            RootHolder ck = factory2.create();
+            ck.setFinancialTransactionKeeper(new AtomicArray<FTrHolder>(FTrHolder.class, 20));
+
+
+            financialTransactionKeeper = ck.getFinancialTransactionKeeper();
+            for (int i = 0; i < 20; i++) {
+
+                FTrHolder f1 = factory3.create();
+                f1.setCounter(1);
+                f1.setFinancialTransactionKeeper(new AtomicArray<FinancialTransactionDS>(FinancialTransactionDS.class, 5));
+                for (int j = 0; j < 5; j++) {
+                    FinancialTransactionDS ftk = factory.create();
+                    ftk.setBuyer("");
+                    ftk.setSeller("");
+                    ftk.setSoldShare(0);
+                    AtomicArray<FinancialTransactionDS> tmp = f1.getFinancialTransactionKeeper();
+                    tmp.set(j, ftk);
+                }
+                financialTransactionKeeper.set(i, f1);
+            }
+       // } catch (FileNotFoundException ex) {
+       //     Logger.getLogger(FinancialTransactiondstm2Special.class.getName()).log(Level.SEVERE, null, ex);
+      //  }
+
+    }
+
+    protected void execute(Vector arguments) {
+        try {
+
+            String oldowner = (String) arguments.get(0);
+            Integer stocktrade = (Integer) arguments.get(1);
+            String newowner = (String) arguments.get(2);
+            String nameofstock = (String) arguments.get(3);
+            SpecialTransactionalFile file = (SpecialTransactionalFile) arguments.get(4);
+            Integer offset1 = (Integer) benchmark.m4.get(oldowner);
+            Integer offset2 = (Integer) benchmark.m4.get(newowner);
+            
+            
+            
+             int i;
+            for (i = 0; i < benchmark.stocks.length; i++) {
+                if (benchmark.stocks[i].equalsIgnoreCase(nameofstock)) {
+                    break;
+                }
+            }
+
+            switch (financialTransactionKeeper.get(i).getCounter()) {
+                case 1:
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setSeller(oldowner);
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setSoldShare(stocktrade.intValue());
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setBuyer(newowner);
+                    financialTransactionKeeper.get(i).setCounter(2);
+                    break;
+                case 2:
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setSeller(oldowner);
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setSoldShare(stocktrade.intValue());
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setBuyer(newowner);
+                    financialTransactionKeeper.get(i).setCounter(3);
+                    break;
+                case 3:
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setSeller(oldowner);
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setSoldShare(stocktrade.intValue());
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setBuyer(newowner);
+                    financialTransactionKeeper.get(i).setCounter(4);
+                    break;
+                case 4:
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setSeller(oldowner);
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setSoldShare(stocktrade.intValue());
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setBuyer(newowner);
+                    financialTransactionKeeper.get(i).setCounter(5);
+                    break;
+                case 5:
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setSeller(oldowner);
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setSoldShare(stocktrade.intValue());
+                    financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setBuyer(newowner);
+                    financialTransactionKeeper.get(i).setCounter(1);
+                    break;
+
+            }
+
+            file.seek(offset1 * Defaults.FILEFRAGMENTSIZE);
+            Vector v = computeandupdate(true, stocktrade, nameofstock, file);
+            String st = (String) (v.get(1));
+            long offset1towrite = ((Long) (v.get(0))).longValue();
+            file.seek(offset2 * Defaults.FILEFRAGMENTSIZE);
+            v = computeandupdate(false, stocktrade, nameofstock, file);
+            String st2 = (String) (v.get(1));
+            long offset2towrite = ((Long) (v.get(0))).longValue();
+
+
+            file.seek(offset1towrite);
+            file.write(st.getBytes());
+            file.seek(offset2towrite);
+            file.write(st2.getBytes());
+
+            String towrite = oldowner + " " + stocktrade.toString() + " " + newowner + " " + nameofstock + " processed\n";
+            //file2.write(towrite.getBytes());
+      
+
+        } catch (IOException ex) {
+            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+        }
+    }
+
+    private Vector computeandupdate(boolean type, Integer stocktrade, String origstockname, SpecialTransactionalFile file) {
+      try {
+            // try{
+            //    RandomAccessFile file = (RandomAccessFile) benchmark.m.get("7");
+            //TransactionalFile file = (TransactionalFile) benchmark.m.get("5");
+        //    TransactionalFile file = (TransactionalFile) benchmark.m.get("accountbalance");
+            Vector v = new Vector();
+            byte[] data = new byte[11];
+            char[] balance = new char[20];
+
+            int counter =0;
+            file.read(data);
+            int adad;
+            for (adad =0; adad < benchmark.stocks.length; adad++) {
+                if (benchmark.stocks[adad].equalsIgnoreCase(origstockname)) {
+                    break;
+                }
+            }
+            file.skipBytes(adad*41);
+            data = new byte[41];
+            file.read(data);
+            int i =0;
+            while (true) {
+                    i = 0;
+                    char[] stname = new char[10];
+                    int ol = 0;
+                   // System.out.println("char " + (char)data[i]);
+                    while (data[i] != ' ') {
+                            stname[ol] = (char) data[i];
+                         //   System.out.println(ol);
+                            ol++;
+                            i++;
+                     
+                    }
+                   
+                    String stockname = String.copyValueOf(stname, 0, ol);
+                    if (stockname.equalsIgnoreCase(origstockname)) {
+                        break;
+                    }
+                    else{ 
+                        System.out.println("WTF??");
+            //            file.read(data);
+                    }
+            }
+
+
+
+
+
+            while ((char) data[i] != ':') {
+                 i++;
+            }
+
+            i++;
+            long offsetofnumber = file.getFilePointer();
+            offsetofnumber += i-40;
+            //file.seek(offsetofnumber);
+            //byte[] k = new byte[4];
+            //file.read(k);
+            //System.out.println("k1 " + (char)k[0]);
+            //System.out.println("k2 " + (char)k[1]);
+            //System.out.println("k3 " + (char)k[2]);
+            //System.out.println("k4 " + (char)k[3]);
+            do {
+                //System.out.println("d " + (char) data[i]);
+                i++;
+                balance[counter] = (char) data[i];
+                counter++;
+            } while (Character.isDigit((char) data[i]) || (char) data[i] == '-');
+
+            int oldbalance = Integer.parseInt(String.valueOf(balance, 0, counter - 1));
+
+            //    return oldnumber;
+
+            int newnumber;
+            if (type) {
+                newnumber = oldbalance - stocktrade.intValue();
+            } else {
+                newnumber = oldbalance + stocktrade.intValue();
+
+
+                //////   file.seek(offsetofnumber);
+            }
+            String st = new String();
+            st = String.valueOf(newnumber);
+            if (String.valueOf(newnumber).length() < counter - 1) {
+
+                for (int j = 0; j < counter - String.valueOf(newnumber).length(); j++) {
+                    st += (new String(" "));
+                }
+            }
+
+            v.add(Long.valueOf(offsetofnumber));
+            v.add(st);
+            return v;
+
+        } catch (IOException ex) {
+            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+            return null;
+        }
+
+
+    }
+
+    protected void printResults() {
+
+        for (int i = 0; i < 20; i++) {
+            System.out.println("----------------------------------------------");
+            System.out.println(benchmark.stocks[i]);
+            for (int j = 0; j < 5; j++) {
+                System.out.print(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getSeller() + " ");
+                System.out.print(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getBuyer() + " ");
+                System.out.println(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getSoldShare());
+            }
+            System.out.println("----------------------------------------------");
+        }
+
+    }
+
+    @atomic
+    public interface FinancialTransactionDS {
+
+        String getSeller();
+
+        void setSeller(String value);
+
+        int getSoldShare();
+
+        void setSoldShare(int value);
+
+        String getBuyer();
+
+        void setBuyer(String value);
+    }
+
+    @atomic
+    public interface FTrHolder {
+
+        AtomicArray<FinancialTransactionDS> getFinancialTransactionKeeper();
+
+        void setFinancialTransactionKeeper(AtomicArray<FinancialTransactionDS> arr);
+
+        int getCounter();
+
+        void setCounter(int value);
+    }
+
+    @atomic
+    public interface RootHolder {
+
+        AtomicArray<FTrHolder> getFinancialTransactionKeeper();
+
+        void setFinancialTransactionKeeper(AtomicArray<FTrHolder> arr);
+        //  int getCounter();
+        //  void setCounter(int value);
+    }
+
+    class LockedFinancialTransactionDS {
+
+        public String seller;
+        public String buyer;
+        public int soldshare;
+    }
+
+    class LockedFTrHolder {
+
+        public LockedFinancialTransactionDS[] lk = new LockedFinancialTransactionDS[5];
+        public int counter;
+    }
+
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransactiondstm2version.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransactiondstm2version.java
new file mode 100644 (file)
index 0000000..a503c16
--- /dev/null
@@ -0,0 +1,590 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.Defaults;
+import dstm2.AtomicArray;
+import dstm2.atomic;
+import dstm2.Thread;
+import dstm2.factory.Factory;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.Vector;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+
+/**
+ *
+ * @author navid
+ */
+public class FinancialTransactiondstm2version extends CustomBenchmark{
+     private static Factory<FinancialTransactionDS> factory = Thread.makeFactory(FinancialTransactionDS.class);
+     private static Factory<RootHolder> factory2 = Thread.makeFactory(RootHolder.class);
+     private static Factory<FTrHolder> factory3 = Thread.makeFactory(FTrHolder.class);
+     
+     LockedFTrHolder[] hlm;
+     RandomAccessFile file;
+     RandomAccessFile file2;
+     
+     
+     
+ /*    String buyer1 = new String();
+     int soldshare1 = 0;
+     String seller1 = new String();
+     
+     String buyer2 = new String();
+     int soldshare2 = 0;
+     String seller2 = new String();
+     
+     String buyer3 = new String();
+     int soldshare3 = 0;
+     String seller3 = new String();
+     
+     String buyer4 = new String();
+     int soldshare4 = 0;
+     String seller4 = new String();
+     
+     String buyer5 = new String();
+     int soldshare5 = 0;
+     String seller5 = new String();
+     
+     int lockedcounter = 1;*/
+     AtomicArray<FTrHolder> financialTransactionKeeper;
+
+    protected void init() {
+        try {
+            // hlm = new LockedFTrHolder[20];
+            /*  for (int i=0; i<20; i++){
+            hlm[i] = new LockedFTrHolder();
+            hlm[i].counter =1;
+            hlm[i].lk = new LockedFinancialTransactionDS[5];
+            for (int j=0; j<5; j++){
+            hlm[i].lk[j] = new LockedFinancialTransactionDS();
+            hlm[i].lk[j].buyer = "";
+            hlm[i].lk[j].seller = "";
+            hlm[i].lk[j].soldshare = 0;
+            }
+            }*/
+
+
+
+            file = new RandomAccessFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/accountbalance.text", "rw");
+            file2 = new RandomAccessFile("/scratch/TransactionalIO/FinancialTransactionBenchmarkFiles/financialtransactionlog.text", "rw");
+
+            RootHolder ck = factory2.create();
+            ck.setFinancialTransactionKeeper(new AtomicArray<FTrHolder>(FTrHolder.class, 20));
+
+
+            financialTransactionKeeper = ck.getFinancialTransactionKeeper();
+            for (int i = 0; i < 20; i++) {
+
+                FTrHolder f1 = factory3.create();
+                f1.setCounter(1);
+                f1.setFinancialTransactionKeeper(new AtomicArray<FinancialTransactionDS>(FinancialTransactionDS.class, 5));
+                for (int j = 0; j < 5; j++) {
+                    FinancialTransactionDS ftk = factory.create();
+                    ftk.setBuyer("");
+                    ftk.setSeller("");
+                    ftk.setSoldShare(0);
+                    AtomicArray<FinancialTransactionDS> tmp = f1.getFinancialTransactionKeeper();
+                    tmp.set(j, ftk);
+                }
+
+
+                financialTransactionKeeper.set(i, f1);
+            }
+        } catch (FileNotFoundException ex) {
+            Logger.getLogger(FinancialTransactiondstm2version.class.getName()).log(Level.SEVERE, null, ex);
+        }
+    }
+
+
+    protected void execute(Vector arguments) {
+        try {
+
+            //TransactionalFile file = (TransactionalFile) benchmark.m.get("5");
+            //RandomAccessFile file = (RandomAccessFile) benchmark.m.get("7");
+            RandomAccessFile file = (RandomAccessFile) benchmark.m.get("accountbalancerandom");
+            String oldowner = (String) arguments.get(0);
+            Integer stocktrade = (Integer) arguments.get(1);
+            String newowner = (String) arguments.get(2);
+            String nameofstock = (String) arguments.get(3);
+            Integer offset1 = (Integer) benchmark.m4.get(oldowner);
+            Integer offset2 = (Integer) benchmark.m4.get(newowner);
+            
+      
+            file.seek(offset1 * Defaults.FILEFRAGMENTSIZE);
+            Vector v = computeandupdate(true, stocktrade, nameofstock);
+            String st = (String)(v.get(1));
+            long offset1towrite = ((Long)(v.get(0))).longValue();
+            
+            file.seek(offset2 * Defaults.FILEFRAGMENTSIZE);
+            v = computeandupdate(false, stocktrade, nameofstock);
+            String st2 = (String)(v.get(1));
+            long offset2towrite = ((Long)(v.get(0))).longValue();
+            
+            
+            file.seek(offset1towrite);
+            file.write(st.getBytes());
+            file.seek(offset2towrite);
+            file.write(st2.getBytes());
+            
+           //RandomAccessFile file2 = (RandomAccessFile) benchmark.m.get("8");
+            RandomAccessFile file2 = (RandomAccessFile) benchmark.m.get("financialtransactionlograndom");
+        //   TransactionalFile file2 = (TransactionalFile) benchmark.m.get("6");
+            
+            String towrite = oldowner + " " + stocktrade.toString() + " " + newowner + " " + nameofstock + " processed\n";
+            file2.write(towrite.getBytes());
+            /*switch(lockedcounter){
+                case 1:
+                      seller1 = oldowner;
+                      soldshare1 = stocktrade.intValue();
+                      buyer1 = newowner;
+                      lockedcounter = 2;
+                      break;
+                case 2:
+                      seller2 = oldowner;
+                      soldshare2 = stocktrade.intValue();
+                      buyer2 = newowner;
+                      lockedcounter = 3;
+                      break;
+                case 3:
+                      seller3 = oldowner;
+                      soldshare3 = stocktrade.intValue();
+                      buyer3 = newowner;
+                      lockedcounter = 4;
+                      break;
+                case 4:
+                      seller4 = oldowner;
+                      soldshare4 = stocktrade.intValue();
+                      buyer4 = newowner;
+                      lockedcounter = 5;
+                      break;
+                case 5:    
+                      seller5 = oldowner;
+                      soldshare5 = stocktrade.intValue();
+                      buyer5 = newowner;
+                      lockedcounter = 1;
+                      break;
+            }*/
+               int i; 
+               for (i=0;i<benchmark.stocks.length; i++){
+                   if (benchmark.stocks[i].equalsIgnoreCase(nameofstock))
+                       break;
+               }
+         
+            switch(financialTransactionKeeper.get(i).getCounter()){
+                case 1:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(2);
+                      break;
+                case 2:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(3);
+                      break;
+                case 3:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(4);
+                      break;
+                case 4:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(5);
+                      break;
+                case 5:    
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(1);
+                      break;
+
+            }
+               
+        /*     switch(hlm[i].counter){
+                case 1:
+                      hlm[i].lk[0].seller = oldowner;
+                      hlm[i].lk[0].soldshare = stocktrade.intValue();
+                      hlm[i].lk[0].buyer = newowner;
+                      hlm[i].counter = 2;
+                      break;
+                case 2:
+                      hlm[i].lk[1].seller = oldowner;
+                      hlm[i].lk[1].soldshare = stocktrade.intValue();
+                      hlm[i].lk[1].buyer = newowner;
+                      hlm[i].counter = 3;
+                      break;
+                case 3:
+                      hlm[i].lk[2].seller = oldowner;
+                      hlm[i].lk[2].soldshare = stocktrade.intValue();
+                      hlm[i].lk[2].buyer = newowner;
+                      hlm[i].counter = 4;
+                      break;
+                case 4:
+                      hlm[i].lk[3].seller = oldowner;
+                      hlm[i].lk[3].soldshare = stocktrade.intValue();
+                      hlm[i].lk[3].buyer = newowner;
+                      hlm[i].counter = 5;
+                      break;
+                case 5:    
+                      hlm[i].lk[4].seller = oldowner;
+                      hlm[i].lk[4].soldshare = stocktrade.intValue();
+                      hlm[i].lk[4].buyer = newowner;
+                      hlm[i].counter = 1;
+                      break;
+            }*/
+            
+        } catch (IOException ex) {
+            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        }
+        /*catch (NullPointerException e){
+            System.out.println("file?? " + file);
+        System.out.println("offset?? " + offset1);
+       System.out.println(oldowner);
+       System.out.println(Thread.currentThread());
+            e.printStackTrace();
+        }*/
+       /* int oldbalance = getOldBalance();
+       int newnumber =  oldbalance - stocktrade.intValue();
+       updateFile(newnumber);
+   //     System.out.println("offset: " + offset1 + " for: " + oldowner + " old balance: "+ oldbalance);
+        
+        if (oldowner.equals("Smith")){
+            System.out.println("offset: " + offset1 + " for: " + oldowner + " old balance: "+ oldbalance);
+            System.out.println("trade money: " + stocktrade);
+        }
+       // System.out.println("old number: " + oldbalance);
+        
+        
+        oldbalance = getOldBalance();
+        newnumber = oldbalance + stocktrade.intValue();
+        updateFile(newnumber);*/
+       /* if (newowner.equals("Smith")){
+            System.out.println("offset: " + offset2 + " for: " + newowner + " old balance: "+ oldbalance);
+               System.out.println("trade money: " + stocktrade);
+        }*/
+        
+          
+            
+      //  }
+
+   // }
+
+    private Vector computeandupdate(boolean type, Integer stocktrade, String origstockname ){
+        try {
+            // try{
+            //RandomAccessFile file = (RandomAccessFile) benchmark.m.get("7");
+            RandomAccessFile file = (RandomAccessFile) benchmark.m.get("accountbalancerandom");
+            
+        //    TransactionalFile file = (TransactionalFile) benchmark.m.get("5");
+            Vector v = new Vector();
+            byte[] data = new byte[1];
+            char[] balance = new char[20];
+
+            // int counter =0;
+            boolean flag = false;
+            data[0] = 'a';
+            int counter = 0;
+            while (data[0] != '\n') {
+                try {
+                    int res;
+                    res = file.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                } catch (IOException ex) {
+                    Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+
+            while (true) {
+                try {
+                    char[] stname = new char[20];
+                    data[0] = 'a';
+                    int ol = 0;
+                    while (data[0] != ' ') {
+                        try {
+                            int res;
+                            res = file.read(data);
+                            if (res == -1) {
+                                flag = true;
+                                break;
+                            }
+                            stname[ol] = (char) data[0];
+                            ol++;
+                        } catch (IOException ex) {
+                            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                        }
+                    }
+                    String stockname = String.copyValueOf(stname, 0, ol - 1);
+                    if (stockname.equalsIgnoreCase(origstockname)) {
+                        break;
+                    } else {
+                        while (data[0] != '\n') {
+                            file.read(data);
+                        }
+                    }
+                } catch (IOException ex) {
+                    Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+
+
+
+
+            data[0] = 'a';
+            while ((char) data[0] != ':') {
+                try {
+                    int res;
+                    res = file.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                } catch (IOException ex) {
+                    Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+            int res = file.read(data);
+            long offsetofnumber = file.getFilePointer();
+            do {
+                res = file.read(data);
+                if (res == -1) {
+                    flag = true;
+                    break;
+                }
+                balance[counter] = (char) data[0];
+                counter++;
+            } while (Character.isDigit((char) data[0]) || (char) data[0] == '-');
+
+            int oldbalance = Integer.parseInt(String.valueOf(balance, 0, counter - 1));
+
+            //    return oldnumber;
+
+            int newnumber;
+            if (type) {
+                newnumber = oldbalance - stocktrade.intValue();
+            } else {
+                newnumber = oldbalance + stocktrade.intValue();
+
+
+                //////   file.seek(offsetofnumber);
+            }
+            String st = new String();
+            st = String.valueOf(newnumber);
+            if (String.valueOf(newnumber).length() < counter - 1) {
+
+                for (int i = 0; i < counter - String.valueOf(newnumber).length(); i++) {
+                    st += (new String(" "));
+                    //file.write((new String(" ")).getBytes());
+                }
+            }
+            //     st += new String("\n");
+            //file.write((new String("\n")).getBytes());
+            v.add(Long.valueOf(offsetofnumber));
+            v.add(st);
+            return v;
+//            } catch (IOException ex) {
+            //         Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+            ///            return null;
+            //    }
+        } catch (IOException ex) {
+            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+            return null;
+        }
+//            } catch (IOException ex) {
+               
+       //         Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+       ///            return null;
+        //    }
+    }
+
+    protected  void printResults() {
+      
+     for (int i=0; i<20; i++){   
+        System.out.println("----------------------------------------------");  
+        System.out.println(benchmark.stocks[i]);  
+        for (int j=0; j<5; j++)
+        {
+            System.out.print(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getSeller() + " ");
+            System.out.print(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getBuyer() + " ");
+            System.out.println(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getSoldShare());
+        }
+        System.out.println("----------------------------------------------");
+      }
+    /*    for (int i=0; i<20; i++){ 
+            System.out.println("----------------------------------------------");  
+            System.out.println(benchmark.stocks[i]);  
+            for (int j=0; j<5; j++)
+            {
+                 
+                System.out.print(hlm[i].lk[j].seller + " ");
+                System.out.print(hlm[i].lk[j].buyer + " ");
+                System.out.println(hlm[i].lk[j].soldshare);
+            }
+            System.out.println("----------------------------------------------");
+        }*/
+        
+      /*  System.out.print(finance1.getSeller() + " ");
+        System.out.print(finance1.getBuyer() + " ");
+        System.out.println(finance1.getSoldShare());
+        
+        System.out.print(finance2.getSeller() + " ");
+        System.out.print(finance2.getBuyer()+ " ");
+        System.out.println(finance2.getSoldShare());
+        
+        System.out.print(finance3.getSeller() + " ");
+        System.out.print(finance3.getBuyer()+ " ");
+        System.out.println(finance3.getSoldShare());
+        
+        System.out.print(finance4.getSeller() + " ");
+        System.out.print(finance4.getBuyer()+ " ");
+        System.out.println(finance4.getSoldShare());
+        
+        System.out.print(finance5.getSeller() + " ");
+        System.out.print(finance5.getBuyer()+ " ");
+        System.out.println(finance5.getSoldShare());*/
+      
+        /*System.out.print(buyer1 + " ");
+        System.out.print(soldshare1 + " ");
+        System.out.println(seller1);
+        
+        System.out.print(buyer2 + " ");
+        System.out.print(soldshare2 + " ");
+        System.out.println(seller2);
+        
+        System.out.print(buyer3 + " ");
+        System.out.print(soldshare3 + " ");
+        System.out.println(seller3);
+        
+        System.out.print(buyer4 + " ");
+        System.out.print(soldshare4 + " ");
+        System.out.println(seller4);
+        
+        System.out.print(buyer5 + " ");
+        System.out.print(soldshare5 + " ");
+        System.out.println(seller5);*/
+        
+        //System.out.println("----------------------------------------------");
+    }
+    
+
+    
+    
+      @atomic public interface FinancialTransactionDS{
+        String getSeller();
+        void setSeller(String value);
+        int getSoldShare();
+        void setSoldShare(int value);
+        String getBuyer();
+        void setBuyer(String value);  
+      }
+      
+      @atomic public interface FTrHolder{
+          AtomicArray<FinancialTransactionDS> getFinancialTransactionKeeper();
+          void setFinancialTransactionKeeper(AtomicArray<FinancialTransactionDS> arr);
+          int getCounter();
+          void setCounter(int value);
+      }
+      
+      @atomic public interface RootHolder{
+          AtomicArray<FTrHolder> getFinancialTransactionKeeper();
+          void setFinancialTransactionKeeper(AtomicArray<FTrHolder> arr);
+        //  int getCounter();
+        //  void setCounter(int value);
+      }
+      
+      class LockedFinancialTransactionDS{
+          public String seller;
+          public String buyer;
+          public int soldshare;          
+      }
+      
+      class LockedFTrHolder{
+          public LockedFinancialTransactionDS[] lk = new LockedFinancialTransactionDS[5];
+          public int counter;
+      }
+      
+      
+      
+      
+      /*    private int getOldBalance(){
+         
+         byte[] data = new byte[1];
+         char[] balance = new char[20];
+         
+        // int counter =0;
+         boolean flag = false;
+         data[0] = 'a';
+         counter = 0;
+         while (data[0] != '\n') {
+                int res;
+                res = file.read(data);
+                if (res == -1) {
+                    flag = true;
+                    break;
+                }
+            }
+        while ((char) data[0] != ':') {
+            int res;
+            res = file.read(data);
+            if (res == -1) {
+                flag = true;
+                break;
+            }
+        }
+        int res = file.read(data);
+        offsetofnumber = file.getFilePointer();
+        do {
+            res = file.read(data);
+            if (res == -1) {
+                flag = true;
+                break;
+            }
+            balance[counter] = (char) data[0];
+            counter++;
+        } while (Character.isDigit((char) data[0]) || (char)data[0] == '-');
+     //   System.out.println((char)data[0]);
+            int oldnumber = Integer.parseInt(String.valueOf(balance, 0, counter - 1));
+       //     System.out.println(oldnumber);
+            return oldnumber;
+            
+
+    }
+    
+    private void updateFile(int newnumber){
+        try {
+            
+            file.seek(offsetofnumber);
+         //   System.out.println(String.valueOf(newnumber));
+            file.write(String.valueOf(newnumber).getBytes());
+            if (String.valueOf(newnumber).length() < counter - 1){
+             
+                for (int i=0; i<counter-String.valueOf(newnumber).length(); i++){
+                  
+                    file.write((new String(" ")).getBytes());
+                }
+            }
+            file.write((new String("\n")).getBytes());
+   
+            } catch (IOException ex) {
+                Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+            }
+    }*/
+
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransactionv2.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/FinancialTransactionv2.java
new file mode 100644 (file)
index 0000000..8ba8677
--- /dev/null
@@ -0,0 +1,573 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.Defaults;
+import TransactionalIO.core.TransactionalFile;
+import dstm2.AtomicArray;
+import dstm2.atomic;
+import dstm2.Thread;
+import dstm2.factory.Factory;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.Vector;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+
+/**
+ *
+ * @author navid
+ */
+public class FinancialTransactionv2 extends CustomBenchmark{
+
+     private static Factory<FinancialTransactionDS> factory = Thread.makeFactory(FinancialTransactionDS.class);
+     private static Factory<RootHolder> factory2 = Thread.makeFactory(RootHolder.class);
+     private static Factory<FTrHolder> factory3 = Thread.makeFactory(FTrHolder.class);
+     
+     LockedFTrHolder[] hlm;
+     
+     
+ /*    String buyer1 = new String();
+     int soldshare1 = 0;
+     String seller1 = new String();
+     
+     String buyer2 = new String();
+     int soldshare2 = 0;
+     String seller2 = new String();
+     
+     String buyer3 = new String();
+     int soldshare3 = 0;
+     String seller3 = new String();
+     
+     String buyer4 = new String();
+     int soldshare4 = 0;
+     String seller4 = new String();
+     
+     String buyer5 = new String();
+     int soldshare5 = 0;
+     String seller5 = new String();
+     
+     int lockedcounter = 1;*/
+     AtomicArray<FTrHolder> financialTransactionKeeper;
+
+    protected void init() {
+       // hlm = new LockedFTrHolder[20];
+      /*  for (int i=0; i<20; i++){
+            hlm[i] = new LockedFTrHolder();
+            hlm[i].counter =1;
+            hlm[i].lk = new LockedFinancialTransactionDS[5];
+            for (int j=0; j<5; j++){
+                hlm[i].lk[j] = new LockedFinancialTransactionDS();
+                hlm[i].lk[j].buyer = "";
+                hlm[i].lk[j].seller = "";
+                hlm[i].lk[j].soldshare = 0;
+            }
+                
+        }*/
+        
+        
+
+        
+        RootHolder ck =  factory2.create();
+        ck.setFinancialTransactionKeeper(new AtomicArray<FTrHolder>(FTrHolder.class, 20));
+        
+
+        financialTransactionKeeper = ck.getFinancialTransactionKeeper();
+        for (int i=0; i<20; i++){ 
+           
+            FTrHolder f1 = factory3.create();
+            f1.setCounter(1);
+            f1.setFinancialTransactionKeeper(new AtomicArray<FinancialTransactionDS>(FinancialTransactionDS.class, 5));
+            for (int j=0; j<5; j++)
+            {
+                FinancialTransactionDS ftk = factory.create();
+                ftk.setBuyer("");
+                ftk.setSeller("");
+                ftk.setSoldShare(0);
+                AtomicArray<FinancialTransactionDS> tmp = f1.getFinancialTransactionKeeper();
+                tmp.set(j, ftk);
+            }
+          
+            
+            financialTransactionKeeper.set(i, f1);
+       }
+    }
+
+
+    protected void execute(Vector arguments) {
+        try {
+
+            //TransactionalFile file = (TransactionalFile) benchmark.m.get("5");
+            
+           // TransactionalFile file = (TransactionalFile) benchmark.m.get("accountbalance");
+        //    RandomAccessFile file = (RandomAccessFile) benchmark.m.get("7");
+            String oldowner = (String) arguments.get(0);
+            Integer stocktrade = (Integer) arguments.get(1);
+            String newowner = (String) arguments.get(2);
+            String nameofstock = (String) arguments.get(3);
+            TransactionalFile file = (TransactionalFile) arguments.get(4);
+            Integer offset1 = (Integer) benchmark.m4.get(oldowner);
+            Integer offset2 = (Integer) benchmark.m4.get(newowner);
+        
+      
+            file.seek(offset1 * Defaults.FILEFRAGMENTSIZE);
+            Vector v = computeandupdate(true, stocktrade, nameofstock, file);
+            String st = (String)(v.get(1));
+            long offset1towrite = ((Long)(v.get(0))).longValue();
+            
+            file.seek(offset2 * Defaults.FILEFRAGMENTSIZE);
+            v = computeandupdate(false, stocktrade, nameofstock, file);
+            String st2 = (String)(v.get(1));
+            long offset2towrite = ((Long)(v.get(0))).longValue();
+            
+            
+            file.seek(offset1towrite);
+            file.write(st.getBytes());
+            file.seek(offset2towrite);
+            file.write(st2.getBytes());
+            
+            String towrite = oldowner + " " + stocktrade.toString() + " " + newowner + " " + nameofstock + " processed\n";
+           
+            
+               int i; 
+               for (i=0;i<benchmark.stocks.length; i++){
+                   if (benchmark.stocks[i].equalsIgnoreCase(nameofstock))
+                       break;
+               }
+                switch(financialTransactionKeeper.get(i).getCounter()){
+                case 1:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(0).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(2);
+                      break;
+                case 2:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(1).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(3);
+                      break;
+                case 3:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(2).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(4);
+                      break;
+                case 4:
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(3).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(5);
+                      break;
+                case 5:    
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setSeller(oldowner);
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setSoldShare(stocktrade.intValue());
+                      financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(4).setBuyer(newowner);
+                      financialTransactionKeeper.get(i).setCounter(1);
+                      break;
+            }
+            
+        } catch (IOException ex) {
+            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        }
+
+
+   /* private Vector computeandupdate(boolean type, Integer stocktrade, String origstockname ){
+        try {
+            // try{
+            //    RandomAccessFile file = (RandomAccessFile) benchmark.m.get("7");
+            //TransactionalFile file = (TransactionalFile) benchmark.m.get("5");
+        //    TransactionalFile file = (TransactionalFile) benchmark.m.get("accountbalance");
+            Vector v = new Vector();
+            byte[] data = new byte[1];
+            char[] balance = new char[20];
+
+            // int counter =0;
+            boolean flag = false;
+            data[0] = 'a';
+            int counter = 0;
+            while (data[0] != '\n') {
+                try {
+                    int res;
+                    res = file.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                } catch (IOException ex) {
+                    Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+
+            while (true) {
+                try {
+                    char[] stname = new char[10];
+                    data[0] = 'a';
+                    int ol = 0;
+                    while (data[0] != ' ') {
+                        try {
+                            int res;
+                            res = file.read(data);
+                            if (res == -1) {
+                                flag = true;
+                                break;
+                            }
+                            stname[ol] = (char) data[0];
+                            ol++;
+                        } catch (IOException ex) {
+                            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                        }
+                    }
+                    String stockname = String.copyValueOf(stname, 0, ol - 1);
+                    if (stockname.equalsIgnoreCase(origstockname)) {
+                        break;
+                    } else {
+                        while (data[0] != '\n') {
+                            file.read(data);
+                        }
+                    }
+                } catch (IOException ex) {
+                    Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+
+
+
+
+            data[0] = 'a';
+            while ((char) data[0] != ':') {
+                try {
+                    int res;
+                    res = file.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                } catch (IOException ex) {
+                    Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+                }
+            }
+            int res = file.read(data);
+            long offsetofnumber = file.getFilePointer();
+            do {
+                res = file.read(data);
+                if (res == -1) {
+                    flag = true;
+                    break;
+                }
+                balance[counter] = (char) data[0];
+                counter++;
+            } while (Character.isDigit((char) data[0]) || (char) data[0] == '-');
+
+            int oldbalance = Integer.parseInt(String.valueOf(balance, 0, counter - 1));
+
+            //    return oldnumber;
+
+            int newnumber;
+            if (type) {
+                newnumber = oldbalance - stocktrade.intValue();
+            } else {
+                newnumber = oldbalance + stocktrade.intValue();
+
+
+                //////   file.seek(offsetofnumber);
+            }
+            String st = new String();
+            st = String.valueOf(newnumber);
+            if (String.valueOf(newnumber).length() < counter - 1) {
+
+                for (int i = 0; i < counter - String.valueOf(newnumber).length(); i++) {
+                    st += (new String(" "));
+                }
+            }
+
+            v.add(Long.valueOf(offsetofnumber));
+            v.add(st);
+            return v;
+
+        } catch (IOException ex) {
+            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+            return null;
+        }
+
+    }*/
+    
+     private Vector computeandupdate(boolean type, Integer stocktrade, String origstockname, TransactionalFile file ){
+        try {
+            // try{
+            //    RandomAccessFile file = (RandomAccessFile) benchmark.m.get("7");
+            //TransactionalFile file = (TransactionalFile) benchmark.m.get("5");
+        //    TransactionalFile file = (TransactionalFile) benchmark.m.get("accountbalance");
+            Vector v = new Vector();
+            byte[] data = new byte[11];
+            char[] balance = new char[20];
+
+            int counter =0;
+            file.read(data);
+            
+            int adad; 
+            for (adad=0;adad<benchmark.stocks.length; adad++){
+                if (benchmark.stocks[adad].equalsIgnoreCase(origstockname))
+                    break;
+            }
+            file.skipBytes(adad*41);
+            
+            data = new byte[41];
+            file.read(data);
+            int i =0;
+            while (true) {
+                    i = 0;
+                    char[] stname = new char[10];
+                    int ol = 0;
+                   // System.out.println("char " + (char)data[i]);
+                    while (data[i] != ' ') {
+                            stname[ol] = (char) data[i];
+                         //   System.out.println(ol);
+                            ol++;
+                            i++;
+                     
+                    }
+                   
+                    String stockname = String.copyValueOf(stname, 0, ol);
+                    if (stockname.equalsIgnoreCase(origstockname)) {
+                        break;
+                    }
+                    else{ 
+                      //  file.read(data);
+                        System.out.println("WTF??!!");
+                    }
+            }
+
+
+
+
+
+            while ((char) data[i] != ':') {
+                 i++;
+            }
+
+            i++;
+            long offsetofnumber = file.getFilePointer();
+            offsetofnumber += i-40;
+       
+            do {
+                //System.out.println("d " + (char) data[i]);
+                i++;
+                balance[counter] = (char) data[i];
+                counter++;
+            } while (Character.isDigit((char) data[i]) || (char) data[i] == '-');
+
+            int oldbalance = Integer.parseInt(String.valueOf(balance, 0, counter - 1));
+
+            //    return oldnumber;
+
+            int newnumber;
+            if (type) {
+                newnumber = oldbalance - stocktrade.intValue();
+            } else {
+                newnumber = oldbalance + stocktrade.intValue();
+
+
+                //////   file.seek(offsetofnumber);
+            }
+            String st = new String();
+            st = String.valueOf(newnumber);
+            if (String.valueOf(newnumber).length() < counter - 1) {
+
+                for (int j = 0; j < counter - String.valueOf(newnumber).length(); j++) {
+                    st += (new String(" "));
+                }
+            }
+
+            v.add(Long.valueOf(offsetofnumber));
+            v.add(st);
+            return v;
+
+        } catch (IOException ex) {
+            Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+            return null;
+        }
+
+    }
+
+    protected  void printResults() {
+      
+     for (int i=0; i<20; i++){   
+        System.out.println("----------------------------------------------");  
+        System.out.println(benchmark.stocks[i]);  
+        for (int j=0; j<5; j++)
+        {
+            System.out.print(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getSeller() + " ");
+            System.out.print(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getBuyer() + " ");
+            System.out.println(financialTransactionKeeper.get(i).getFinancialTransactionKeeper().get(j).getSoldShare());
+        }
+        System.out.println("----------------------------------------------");
+      }
+    /*    for (int i=0; i<20; i++){ 
+            System.out.println("----------------------------------------------");  
+            System.out.println(benchmark.stocks[i]);  
+            for (int j=0; j<5; j++)
+            {
+                 
+                System.out.print(hlm[i].lk[j].seller + " ");
+                System.out.print(hlm[i].lk[j].buyer + " ");
+                System.out.println(hlm[i].lk[j].soldshare);
+            }
+            System.out.println("----------------------------------------------");
+        }*/
+        
+      /*  System.out.print(finance1.getSeller() + " ");
+        System.out.print(finance1.getBuyer() + " ");
+        System.out.println(finance1.getSoldShare());
+        
+        System.out.print(finance2.getSeller() + " ");
+        System.out.print(finance2.getBuyer()+ " ");
+        System.out.println(finance2.getSoldShare());
+        
+        System.out.print(finance3.getSeller() + " ");
+        System.out.print(finance3.getBuyer()+ " ");
+        System.out.println(finance3.getSoldShare());
+        
+        System.out.print(finance4.getSeller() + " ");
+        System.out.print(finance4.getBuyer()+ " ");
+        System.out.println(finance4.getSoldShare());
+        
+        System.out.print(finance5.getSeller() + " ");
+        System.out.print(finance5.getBuyer()+ " ");
+        System.out.println(finance5.getSoldShare());*/
+      
+        /*System.out.print(buyer1 + " ");
+        System.out.print(soldshare1 + " ");
+        System.out.println(seller1);
+        
+        System.out.print(buyer2 + " ");
+        System.out.print(soldshare2 + " ");
+        System.out.println(seller2);
+        
+        System.out.print(buyer3 + " ");
+        System.out.print(soldshare3 + " ");
+        System.out.println(seller3);
+        
+        System.out.print(buyer4 + " ");
+        System.out.print(soldshare4 + " ");
+        System.out.println(seller4);
+        
+        System.out.print(buyer5 + " ");
+        System.out.print(soldshare5 + " ");
+        System.out.println(seller5);*/
+        
+        //System.out.println("----------------------------------------------");
+    }
+    
+
+    
+    
+      @atomic public interface FinancialTransactionDS{
+        String getSeller();
+        void setSeller(String value);
+        int getSoldShare();
+        void setSoldShare(int value);
+        String getBuyer();
+        void setBuyer(String value);  
+      }
+      
+      @atomic public interface FTrHolder{
+          AtomicArray<FinancialTransactionDS> getFinancialTransactionKeeper();
+          void setFinancialTransactionKeeper(AtomicArray<FinancialTransactionDS> arr);
+          int getCounter();
+          void setCounter(int value);
+      }
+      
+      @atomic public interface RootHolder{
+          AtomicArray<FTrHolder> getFinancialTransactionKeeper();
+          void setFinancialTransactionKeeper(AtomicArray<FTrHolder> arr);
+        //  int getCounter();
+        //  void setCounter(int value);
+      }
+      
+      class LockedFinancialTransactionDS{
+          public String seller;
+          public String buyer;
+          public int soldshare;          
+      }
+      
+      class LockedFTrHolder{
+          public LockedFinancialTransactionDS[] lk = new LockedFinancialTransactionDS[5];
+          public int counter;
+      }
+      
+      
+      
+      
+      /*    private int getOldBalance(){
+         
+         byte[] data = new byte[1];
+         char[] balance = new char[20];
+         
+        // int counter =0;
+         boolean flag = false;
+         data[0] = 'a';
+         counter = 0;
+         while (data[0] != '\n') {
+                int res;
+                res = file.read(data);
+                if (res == -1) {
+                    flag = true;
+                    break;
+                }
+            }
+        while ((char) data[0] != ':') {
+            int res;
+            res = file.read(data);
+            if (res == -1) {
+                flag = true;
+                break;
+            }
+        }
+        int res = file.read(data);
+        offsetofnumber = file.getFilePointer();
+        do {
+            res = file.read(data);
+            if (res == -1) {
+                flag = true;
+                break;
+            }
+            balance[counter] = (char) data[0];
+            counter++;
+        } while (Character.isDigit((char) data[0]) || (char)data[0] == '-');
+     //   System.out.println((char)data[0]);
+            int oldnumber = Integer.parseInt(String.valueOf(balance, 0, counter - 1));
+       //     System.out.println(oldnumber);
+            return oldnumber;
+            
+
+    }
+    
+    private void updateFile(int newnumber){
+        try {
+            
+            file.seek(offsetofnumber);
+         //   System.out.println(String.valueOf(newnumber));
+            file.write(String.valueOf(newnumber).getBytes());
+            if (String.valueOf(newnumber).length() < counter - 1){
+             
+                for (int i=0; i<counter-String.valueOf(newnumber).length(); i++){
+                  
+                    file.write((new String(" ")).getBytes());
+                }
+            }
+            file.write((new String("\n")).getBytes());
+   
+            } catch (IOException ex) {
+                Logger.getLogger(FinancialTransaction.class.getName()).log(Level.SEVERE, null, ex);
+            }
+    }*/
+
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/IntSetBenchmark.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/IntSetBenchmark.java
new file mode 100644 (file)
index 0000000..8c73ff2
--- /dev/null
@@ -0,0 +1,419 @@
+/*
+ * IntSetBenchmark.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa
+ * Clara, California 95054, U.S.A.  All rights reserved.  
+ * 
+ * Sun Microsystems, Inc. has intellectual property rights relating to
+ * technology embodied in the product that is described in this
+ * document.  In particular, and without limitation, these
+ * intellectual property rights may include one or more of the
+ * U.S. patents listed at http://www.sun.com/patents and one or more
+ * additional patents or pending patent applications in the U.S. and
+ * in other countries.
+ * 
+ * U.S. Government Rights - Commercial software.
+ * Government users are subject to the Sun Microsystems, Inc. standard
+ * license agreement and applicable provisions of the FAR and its
+ * supplements.  Use is subject to license terms.  Sun, Sun
+ * Microsystems, the Sun logo and Java are trademarks or registered
+ * trademarks of Sun Microsystems, Inc. in the U.S. and other
+ * countries.  
+ * 
+ * This product is covered and controlled by U.S. Export Control laws
+ * and may be subject to the export or import laws in other countries.
+ * Nuclear, missile, chemical biological weapons or nuclear maritime
+ * end uses or end users, whether direct or indirect, are strictly
+ * prohibited.  Export or reexport to countries subject to
+ * U.S. embargo or to entities identified on U.S. export exclusion
+ * lists, including, but not limited to, the denied persons and
+ * specially designated nationals lists is strictly prohibited.
+ */
+
+package dstm2.benchmark;
+
+import TransactionalIO.exceptions.AbortedException;
+import TransactionalIO.exceptions.GracefulException;
+import TransactionalIO.exceptions.PanicException;
+import dstm2.Thread;
+
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.TransactionalFile;
+import dstm2.util.Random;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.concurrent.Callable;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * This abstract class is the superclass for the integer set benchmarks.
+ * @author Maurice Herlihy
+ * @date April 2004
+ */
+public abstract class IntSetBenchmark implements Benchmark, Iterable<Integer> {
+  
+  /**
+   * How large to initialize the integer set.
+   */
+  protected final int INITIAL_SIZE = 8;
+  
+  /**
+   * After the run is over, synchronize merging statistics with other threads.
+   */
+  static final Object lock = new Object();
+  /**
+   * local variable
+   */
+  int element;
+  /**
+   * local variable
+   */
+  int value;
+  
+  /**
+   * Number of calls to insert()
+   */
+  int insertCalls = 0;
+  /**
+   * number of calls to contains()
+   */
+  int containsCalls = 0;
+  /**
+   * number of calls to remove()
+   */
+  int removeCalls = 0;
+  /**
+   * amount by which the set size has changed
+   */
+  int delta = 0;
+  
+  /**
+   * Give subclass a chance to intialize private fields.
+   */
+  protected abstract void init();
+  
+  /**
+   * Iterate through set. Not necessarily thread-safe.
+   */
+  public abstract Iterator<Integer> iterator();
+  
+  /**
+   * Add an element to the integer set, if it is not already there.
+   * @param v the integer value to add from the set
+   * @return true iff value was added.
+   */
+  public abstract boolean insert(int v);
+  
+  /**
+   * Tests wheter a value is in an the integer set.
+   * @param v the integer value to insert into the set
+   * @return true iff presence was confirmed.
+   */
+  public abstract boolean contains(int v);
+  
+  /**
+   * Removes an element from the integer set, if it is there.
+   * @param v the integer value to delete from the set
+   * @return true iff v was removed
+   */
+  public abstract boolean remove(int v);
+  
+  /**
+   * Creates a new test thread.
+   * @param percent Mix of mutators and observers.
+   * @return Thread to run.
+   */
+  public Thread createThread(int percent, char sample) {
+    try {
+      TestThread testThread = new TestThread(this, percent, sample);
+      return testThread;
+    } catch (Exception e) {
+      e.printStackTrace(System.out);
+      return null;
+    }
+  }
+  
+  /**
+   * Prints an error message to <code>System.out</code>, including a
+   *  standard header to identify the message as an error message.
+   * @param s String describing error
+   */
+  protected static void reportError(String s) {
+    System.out.println(" ERROR: " + s);
+    System.out.flush();
+  }
+  
+  public void report() {
+    System.out.println("Insert/Remove calls:\t" + (insertCalls + removeCalls));
+    System.out.println("Contains calls:\t" + containsCalls);
+  }
+  
+  private class TestThread extends Thread {
+    IntSetBenchmark intSet;
+    /**
+     * Thread-local statistic.
+     */
+    int myInsertCalls = 0;
+    /**
+     * Thread-local statistic.
+     */
+    int myRemoveCalls = 0;
+    /**
+     * Thread-local statistic.
+     */
+    int myContainsCalls = 0;
+    /**
+     * Thread-local statistic.
+     */
+    int myDelta = 0;        // net change
+    public int percent = 0; // percent inserts
+    char sample;
+    AVLTree tree;
+    
+    TestThread(IntSetBenchmark intSet, int percent, char sample) {
+      this.intSet = intSet;
+      this.percent = percent;
+      this.sample = sample;
+    }
+    
+   
+    
+    public void run() {
+      Random random = new Random(this.hashCode());
+      random.setSeed(System.currentTimeMillis()); // comment out for determinstic
+      
+      boolean toggle = true;
+      final TransactionalFile f1 = (TransactionalFile)benchmark.TransactionalFiles.get("0");
+      try {
+        while (true) {
+          boolean result = true;
+          element = random.nextInt();
+          if (Math.abs(element) % 100 < percent) {
+            if (toggle) {        // insert on even turns
+              value = element / 100;
+              result = Thread.doIt(new Callable<Boolean>() {
+                public Boolean call() {
+                    //////////////////////////////////////////benchmark 1////////////////////////////
+                      /*  TransactionalFile f1 = (TransactionalFile)benchmark.m.get("2");
+                        byte[] data = new byte[1];
+                        char[] holder = new char[10000];
+                        char[] word = new char[20];
+                        boolean flag = false;    
+                        long toseek = Integer.valueOf(Thread.currentThread().getName().substring(7)) * 21169; 
+                        f1.seek(toseek);
+
+                        data[0] ='a';
+                        if (toseek != 0) //////////////// skipt the first word since its been read already
+                            while (data[0] != '\n'){
+                                int res;
+                                res = f1.read(data);
+                                if (res == -1){
+                                    flag =true;
+                                    break;
+                                }
+                            }
+                        
+                        boolean completeword = false;
+                        int counter = 0;
+                        while (f1.getFilePointer() < toseek +21169)
+                        {
+                            if (flag)
+                                break;
+                            data[0] = 'a';
+                            int i = 0;
+                            int res;
+                            while ((data[0] != '\n' || completeword)){
+                                
+                                //if (completeword){
+                                 //  String str = Mixedbecnhmark.processInput(String.valueOf(word,0,counter-1)); 
+                                   //if (str != null){
+                                  // update data structure     
+                                  //  byte[] towrite = new byte[String.valueOf(holder,0,i).length()];
+                                  //  towrite = String.valueOf(holder,0,i).getBytes();
+                                  //  try {                               
+                                 //   ((TransactionalFile) (benchmark.m.get("3"))).write(towrite);         
+                           
+                                  //    } catch (IOException ex) {
+                                  //      Logger.getLogger(TestThread.class.getName()).log(Level.SEVERE, null, ex);
+                                  //      }
+                                  //} 
+                                //}
+                                
+                               if (flag)
+                                    break;
+                                                                
+                               if (completeword){
+                                   synchronized(benchmark.lock){
+                                  //  if  (!(Character.isWhitespace(word[counter])))
+                                      //  System.out.println(String.valueOf(word,0,counter-1));
+                                   }
+                                    holder[i] = (char)data[0];
+                                    i++;
+                                   
+                               }
+                               counter = 0;   
+                               completeword= false;
+                               data[0] = 'a';
+                               while(Character.isLetter((char)data[0]))
+                               {
+                                    
+                                    res = f1.read(data);
+                                    if (res == -1){
+                                        flag = true;
+                                        break;
+                                    }
+                                    word[counter] = (char)data[0];
+                                    counter++;
+                                    if (counter > 1)
+                                        completeword = true;
+                                    holder[i] = (char)data[0];
+                                    i++;
+                               }
+                            }
+
+                        } 
+
+                        myInsertCalls++;
+                        return intSet.insert(464);*/
+                    ////////////////////////benchmark 2///////////////////
+                        
+                    /*    TransactionalFile f1 = (TransactionalFile)benchmark.m.get("0");
+                        byte[] data = new byte[1];
+                        char[] holder = new char[10000];
+                        char[] word = new char[20];
+                        boolean flag = false;    
+                        long toseek = Integer.valueOf(Thread.currentThread().getName().substring(7)) * 20448; 
+                        f1.seek(toseek);
+
+                        data[0] ='a';
+                        if (toseek != 0) //////////////// skipt the first word since its been read already
+                            while (data[0] != '\n'){
+                                int res;
+                                res = f1.read(data);
+                                if (res == -1){
+                                    flag =true;
+                                    break;
+                                }
+                            }
+                        
+                    
+                         while (f1.getFilePointer() < toseek +20448)
+                        {
+                            if (flag == true)
+                                break;
+                            data[0] = 'a';
+                            int i = 0;
+                            int res;
+                            while (data[0] != '\n'){
+                                res = f1.read(data);
+                                if (res == -1){
+                                    flag = true;
+                                    break;
+                                }
+                              
+                                holder[i] = (char)data[0];
+                                i++;
+                            }
+                        
+                            
+                            byte[] towrite = new byte[String.valueOf(holder,0,i).length()];
+                            towrite = String.valueOf(holder,0,i).getBytes();
+                         //   System.out.println(String.valueOf(holder,0,i).toLowerCase().substring(0, 1));
+             
+                            try {
+                                ((TransactionalFile) (benchmark.m.get(String.valueOf(holder,0,i).toLowerCase().substring(0, 1)))).write(towrite);         
+                           //update the memory         //}
+                            } catch (IOException ex) {
+                                Logger.getLogger(TestThread.class.getName()).log(Level.SEVERE, null, ex);
+                            }
+                        }  */
+                      
+                     
+                      
+                    return true;
+
+                }
+              });
+              if (result)
+                myDelta++;
+            }
+            else {   
+                // remove on odd turns
+                
+              result = Thread.doIt(new Callable<Boolean>() {
+                public Boolean call() {  
+                  return intSet.remove(value);
+                }
+              });
+              myRemoveCalls++;
+              if (result)
+                this.myDelta--;
+            }
+            toggle = !toggle;
+          } else {
+            Thread.doIt(new Callable<Void>() {
+              public Void call() {
+                //  return null;
+                intSet.contains(element / 100);
+                return null;
+              }
+            });
+            myContainsCalls++;
+          }
+        }
+      } catch (GracefulException g) {
+        // update statistics
+        synchronized (lock) {
+          
+          insertCalls   += myInsertCalls;
+          removeCalls   += myRemoveCalls;
+          containsCalls += myContainsCalls;
+          delta         += myDelta;
+        }
+        return;
+      }
+    }
+  }
+  
+  public void sanityCheck() {
+    long expected = INITIAL_SIZE + delta;
+    int length = 1;
+    
+    int prevValue = Integer.MIN_VALUE;
+    for (int value : this) {
+      length++;
+      if (value < prevValue) {
+        System.out.println("ERROR: set  not sorted");
+        System.exit(0);
+      }
+      if (value == prevValue) {
+        System.out.println("ERROR: set has duplicates!");
+        System.exit(0);
+      }
+      if (length == expected) {
+        System.out.println("ERROR: set has bad length!");
+        System.exit(0);
+      }
+     
+    }
+    System.out.println("Integer Set OK");
+  }
+  
+  /**
+   * Creates a new IntSetBenchmark
+   */
+  public IntSetBenchmark() {
+    int size = 2;
+    init();
+    Random random = new Random(this.hashCode());
+   while (size < INITIAL_SIZE) {
+      if (insert(random.nextInt())) {
+        size++;
+      }
+    }
+  }
+  
+  public void printTree(){};
+  
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/List.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/List.java
new file mode 100644 (file)
index 0000000..7eae059
--- /dev/null
@@ -0,0 +1,170 @@
+/*
+ * List.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa
+ * Clara, California 95054, U.S.A.  All rights reserved.  
+ * 
+ * Sun Microsystems, Inc. has intellectual property rights relating to
+ * technology embodied in the product that is described in this
+ * document.  In particular, and without limitation, these
+ * intellectual property rights may include one or more of the
+ * U.S. patents listed at http://www.sun.com/patents and one or more
+ * additional patents or pending patent applications in the U.S. and
+ * in other countries.
+ * 
+ * U.S. Government Rights - Commercial software.
+ * Government users are subject to the Sun Microsystems, Inc. standard
+ * license agreement and applicable provisions of the FAR and its
+ * supplements.  Use is subject to license terms.  Sun, Sun
+ * Microsystems, the Sun logo and Java are trademarks or registered
+ * trademarks of Sun Microsystems, Inc. in the U.S. and other
+ * countries.  
+ * 
+ * This product is covered and controlled by U.S. Export Control laws
+ * and may be subject to the export or import laws in other countries.
+ * Nuclear, missile, chemical biological weapons or nuclear maritime
+ * end uses or end users, whether direct or indirect, are strictly
+ * prohibited.  Export or reexport to countries subject to
+ * U.S. embargo or to entities identified on U.S. export exclusion
+ * lists, including, but not limited to, the denied persons and
+ * specially designated nationals lists is strictly prohibited.
+ */
+
+package dstm2.benchmark;
+
+import dstm2.atomic;
+import dstm2.factory.Factory;
+import dstm2.Thread;
+import java.util.Iterator;
+
+/**
+ * @author Maurice Herlihy
+ */
+public class List extends IntSetBenchmark {
+  
+  static Factory<INode> factory = Thread.makeFactory(INode.class);
+  
+  protected INode first;
+  
+  protected void init() {
+    INode firstList  = factory.create();
+    firstList.setValue(Integer.MIN_VALUE);
+    this.first = firstList;
+    INode firstNext = factory.create();
+    firstNext.setValue(Integer.MAX_VALUE);
+    firstList.setNext(firstNext);
+  }
+  
+  /**
+   * This method does all the work. It returns a
+   * <code>dstm.benchmark.IntSetBenchmark.Neighborhood</code> object containing
+   * the transactional node with maximal value strictly less than v, and the
+   * non-transactional TestFactory element containing v (or null, if none exists).
+   * @param v value sought
+   * @return neighborhood of value
+   */
+  protected Neighborhood find(int v) {
+    INode prevNode = this.first;
+    INode currNode = prevNode.getNext();
+    while (currNode.getValue() < v) {
+      prevNode = currNode;
+      currNode = prevNode.getNext();
+    }
+    if (currNode.getValue() == v)
+      return new Neighborhood(prevNode, currNode);
+    else
+      return new Neighborhood(prevNode);
+  }
+  
+  /**
+   * Add an element to the integer set, if it is not already there.
+   * @param v the integer value to add from the set
+   * @return true iff value was added.
+   */
+  public boolean insert(int v) {
+    INode newNode = factory.create();
+    newNode.setValue(v);
+    Neighborhood hood = find(v);
+    if (hood.currNode != null) {
+      return false;
+    } else {
+      INode prevNode = hood.prevNode;
+      newNode.setNext(prevNode.getNext());
+      prevNode.setNext(newNode);
+      return true;
+    }
+  }
+  
+  /**
+   * Tests wheter a value is in an the integer set.
+   * @param v the integer value to insert into the set
+   * @return true iff presence was confirmed.
+   */
+  public boolean contains(int v) {
+    Neighborhood hood = find(v);
+    return hood.currNode != null;
+  }
+  
+  /**
+   * Removes an element from the integer set, if it is there.
+   * @param v the integer value to delete from the set
+   * @return true iff v was removed
+   */
+  public boolean remove(int v) {
+    INode newNode = factory.create();
+    newNode.setValue(v);
+    Neighborhood hood = find(v);
+    if (hood.currNode == null) {
+      return false;
+    } else {
+      INode prevNode = hood.prevNode;
+      prevNode.setNext(hood.currNode.getNext());
+      return true;
+    }
+  }
+  
+  @atomic public interface INode {
+    int getValue();
+    void setValue(int value);
+    INode getNext();
+    void setNext(INode value);
+  }
+  
+  public Iterator<Integer> iterator() {
+    return new Iterator<Integer>() {
+      INode cursor = List.this.first.getNext();
+      public boolean hasNext() {
+        return cursor.getNext().getValue() != Integer.MAX_VALUE;
+      }
+      public Integer next() {
+        INode node = cursor;
+        cursor = cursor.getNext();
+        return node.getValue();
+      }
+      public void remove() {
+        throw new UnsupportedOperationException();
+      }
+      
+    };
+  }
+  protected class Neighborhood {
+    public INode prevNode;
+    public INode currNode;
+    public Neighborhood(INode prevNode, INode currNode) {
+      this.prevNode = prevNode;
+      this.currNode = currNode;
+    }
+    public Neighborhood(INode prevNode) {
+      this.prevNode = prevNode;
+    }
+  }
+
+    public Thread createThread(int which) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+
+
+
+
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/ListRelease.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/ListRelease.java
new file mode 100644 (file)
index 0000000..eea9016
--- /dev/null
@@ -0,0 +1,171 @@
+/*
+ * ListRelease.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa
+ * Clara, California 95054, U.S.A.  All rights reserved.  
+ * 
+ * Sun Microsystems, Inc. has intellectual property rights relating to
+ * technology embodied in the product that is described in this
+ * document.  In particular, and without limitation, these
+ * intellectual property rights may include one or more of the
+ * U.S. patents listed at http://www.sun.com/patents and one or more
+ * additional patents or pending patent applications in the U.S. and
+ * in other countries.
+ * 
+ * U.S. Government Rights - Commercial software.
+ * Government users are subject to the Sun Microsystems, Inc. standard
+ * license agreement and applicable provisions of the FAR and its
+ * supplements.  Use is subject to license terms.  Sun, Sun
+ * Microsystems, the Sun logo and Java are trademarks or registered
+ * trademarks of Sun Microsystems, Inc. in the U.S. and other
+ * countries.  
+ * 
+ * This product is covered and controlled by U.S. Export Control laws
+ * and may be subject to the export or import laws in other countries.
+ * Nuclear, missile, chemical biological weapons or nuclear maritime
+ * end uses or end users, whether direct or indirect, are strictly
+ * prohibited.  Export or reexport to countries subject to
+ * U.S. embargo or to entities identified on U.S. export exclusion
+ * lists, including, but not limited to, the denied persons and
+ * specially designated nationals lists is strictly prohibited.
+ */
+
+package dstm2.benchmark;
+
+import dstm2.atomic;
+import dstm2.factory.Factory;
+import dstm2.Thread;
+import dstm2.factory.Releasable;
+import java.lang.reflect.Method;
+import java.util.Iterator;
+
+/**
+ * @author Maurice Herlihy
+ */
+public class ListRelease extends IntSetBenchmark {
+  
+  static Factory<INode> factory = Thread.makeFactory(INode.class);
+  
+  protected INode first;
+  
+  protected void init() {
+    INode firstList  = factory.create();
+    firstList.setValue(Integer.MIN_VALUE);
+    this.first = firstList;
+    INode firstNext = factory.create();
+    firstNext.setValue(Integer.MAX_VALUE);
+    firstList.setNext(firstNext);
+  }
+  
+  /**
+   * This method does all the work. It returns a
+   * <code>dstm.benchmark.IntSetBenchmark.Neighborhood</code> object containing
+   * the transactional node with maximal value strictly less than v, and the
+   * non-transactional TestFactory element containing v (or null, if none exists).
+   * @param v value sought
+   * @return neighborhood of value
+   */
+  protected Neighborhood find(int v) {
+    INode last = null;
+    INode prev = this.first;
+    INode curr = prev.getNext();
+    while (curr.getValue() < v) {
+      if (last != null) {
+        ((Releasable)last).release();
+      }
+      prev = curr;
+      curr = prev.getNext();
+    }
+    if (curr.getValue() == v)
+      return new Neighborhood(prev, curr);
+    else
+      return new Neighborhood(prev);
+  }
+  
+  /**
+   * Add an element to the integer set, if it is not already there.
+   * @param v the integer value to add from the set
+   * @return true iff value was added.
+   */
+  public boolean insert(int v) {
+    INode newNode = factory.create();
+    newNode.setValue(v);
+    Neighborhood hood = find(v);
+    if (hood.curr != null) {
+      return false;
+    } else {
+      INode prev = hood.prev;
+      newNode.setNext(prev.getNext());
+      prev.setNext(newNode);
+      return true;
+    }
+  }
+  
+  /**
+   * Tests wheter a value is in an the integer set.
+   * @param v the integer value to insert into the set
+   * @return true iff presence was confirmed.
+   */
+  public boolean contains(int v) {
+    Neighborhood hood = find(v);
+    return hood.curr != null;
+  }
+  
+  /**
+   * Removes an element from the integer set, if it is there.
+   * @param v the integer value to delete from the set
+   * @return true iff v was removed
+   */
+  public boolean remove(int v) {
+    INode newNode = factory.create();
+    newNode.setValue(v);
+    Neighborhood hood = find(v);
+    if (hood.curr == null) {
+      return false;
+    } else {
+      INode prev = hood.prev;
+      prev.setNext(hood.curr.getNext());
+      return true;
+    }
+  }
+  
+  @atomic public interface INode {
+    int getValue();
+    void setValue(int value);
+    INode getNext();
+    void setNext(INode value);
+  }
+  
+  public Iterator<Integer> iterator() {
+    return new Iterator<Integer>() {
+      INode cursor = ListRelease.this.first.getNext();
+      public boolean hasNext() {
+        return cursor.getNext().getValue() != Integer.MAX_VALUE;
+      }
+      public Integer next() {
+        INode node = cursor;
+        cursor = cursor.getNext();
+        return node.getValue();
+      }
+      public void remove() {
+        throw new UnsupportedOperationException();
+      }
+      
+    };
+  } 
+  protected class Neighborhood {
+    public INode prev;
+    public INode curr;
+    public Neighborhood(INode prev, INode curr) {
+      this.prev = prev;
+      this.curr = curr;
+    }
+    public Neighborhood(INode prev) {
+      this.prev = prev;
+    }
+  }
+
+    public Thread createThread(int which) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/ListSnap.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/ListSnap.java
new file mode 100644 (file)
index 0000000..eff86ac
--- /dev/null
@@ -0,0 +1,204 @@
+/*
+ * ListSnap.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa
+ * Clara, California 95054, U.S.A.  All rights reserved.  
+ * 
+ * Sun Microsystems, Inc. has intellectual property rights relating to
+ * technology embodied in the product that is described in this
+ * document.  In particular, and without limitation, these
+ * intellectual property rights may include one or more of the
+ * U.S. patents listed at http://www.sun.com/patents and one or more
+ * additional patents or pending patent applications in the U.S. and
+ * in other countries.
+ * 
+ * U.S. Government Rights - Commercial software.
+ * Government users are subject to the Sun Microsystems, Inc. standard
+ * license agreement and applicable provisions of the FAR and its
+ * supplements.  Use is subject to license terms.  Sun, Sun
+ * Microsystems, the Sun logo and Java are trademarks or registered
+ * trademarks of Sun Microsystems, Inc. in the U.S. and other
+ * countries.  
+ * 
+ * This product is covered and controlled by U.S. Export Control laws
+ * and may be subject to the export or import laws in other countries.
+ * Nuclear, missile, chemical biological weapons or nuclear maritime
+ * end uses or end users, whether direct or indirect, are strictly
+ * prohibited.  Export or reexport to countries subject to
+ * U.S. embargo or to entities identified on U.S. export exclusion
+ * lists, including, but not limited to, the denied persons and
+ * specially designated nationals lists is strictly prohibited.
+ */
+
+package dstm2.benchmark;
+//import TransactionalIO.exceptions.AbortedException;
+import TransactionalIO.exceptions.*;//GracefulException;
+import dstm2.atomic;
+import dstm2.benchmark.IntSetBenchmark;
+import dstm2.Thread;
+import dstm2.factory.Factory;
+import dstm2.factory.Snapable;
+import java.lang.reflect.Method;
+import java.util.Iterator;
+import java.util.concurrent.Callable;
+
+/**
+ * @author Maurice Herlihy
+ */
+public class ListSnap extends IntSetBenchmark {
+  
+  static Factory<INode> factory = Thread.makeFactory(INode.class);
+  
+  protected INode first;
+  
+  protected void init() {
+    INode firstList  = factory.create();
+    firstList.setValue(Integer.MIN_VALUE);
+    this.first = firstList;
+    INode firstNext = factory.create();
+    firstNext.setValue(Integer.MAX_VALUE);
+    firstList.setNext(firstNext);
+  }
+  
+  /**
+   * Tests wheter a value is in an the integer set.
+   * @param v the integer value to insert into the set
+   * @return true iff presence was confirmed.
+   */
+  public boolean contains(int v) {
+    INode last = null;
+    INode lastSnap = null;
+    INode prev = this.first;
+    INode prevSnap = ((Snapable<INode>)prev).snapshot();
+    INode curr = prevSnap.getNext();
+    INode currSnap = ((Snapable<INode>)curr).snapshot();
+    while (currSnap.getValue()< v) {
+      if (last != null) {
+        ((Snapable<INode>)last).validate(lastSnap);
+      }
+      last = prev;
+      lastSnap = prevSnap;
+      prev = curr;
+      prevSnap = currSnap;
+      curr = prevSnap.getNext();
+      currSnap = ((Snapable<INode>)curr).snapshot();
+    }
+    if (lastSnap != null) {
+      ((Snapable<INode>)last).upgrade(lastSnap);
+    }
+    ((Snapable<INode>)prev).upgrade(prevSnap);
+    ((Snapable<INode>)curr).upgrade(currSnap);
+    return (curr.getValue()== v);
+  }
+  
+  /**
+   * Removes an element from the integer set, if it is there.
+   * @param v the integer value to delete from the set
+   * @return true iff v was removed
+   */
+  public boolean remove(int v) {
+    INode last = null;
+    INode lastSnap = null;
+    INode prev = this.first;
+    INode prevSnap = ((Snapable<INode>)prev).snapshot();
+    INode curr = prevSnap.getNext();
+    INode currSnap = ((Snapable<INode>)curr).snapshot();
+    while (currSnap.getValue()< v) {
+      if (last != null) {
+        ((Snapable<INode>)last).validate(lastSnap);
+      }
+      last = prev;
+      lastSnap = prevSnap;
+      prev = curr;
+      prevSnap = currSnap;
+      curr = prevSnap.getNext();
+      currSnap = ((Snapable<INode>)curr).snapshot();
+    }
+    if (lastSnap != null) {
+      ((Snapable<INode>)last).upgrade(lastSnap);
+    }
+    ((Snapable<INode>)prev).upgrade(prevSnap);
+    ((Snapable<INode>)curr).upgrade(currSnap);
+    if (curr.getValue()!= v) {
+      return false;
+    } else {
+      prev.setNext(curr.getNext());
+      return true;
+    }
+  }
+  
+  public boolean insert(int v) {
+    INode last = null;
+    INode lastSnap = null;
+    INode prev = this.first;
+    Snapable<INode> prevS = (Snapable<INode>)prev;
+    INode prevSnap = prevS.snapshot();
+    INode curr = prevSnap.getNext();
+    INode currSnap = ((Snapable<INode>)curr).snapshot();
+    INode newNode = factory.create();
+    while (currSnap.getValue()< v) {
+      if (last != null) {
+        ((Snapable<INode>)last).validate(lastSnap);
+      }
+      last = prev;
+      lastSnap = prevSnap;
+      prev = curr;
+      prevSnap = currSnap;
+      curr = prevSnap.getNext();
+      currSnap = ((Snapable<INode>)curr).snapshot();
+    }
+    if (lastSnap != null) {
+      ((Snapable<INode>)last).upgrade(lastSnap);
+    }
+    ((Snapable<INode>)prev).upgrade(prevSnap);
+    ((Snapable<INode>)curr).upgrade(currSnap);
+    if (currSnap.getValue()== v) {
+      return false;
+    } else {
+      newNode.setNext(curr);
+      prev.setNext(newNode);
+      return true;
+    }
+  }
+  
+  public Iterator<Integer> iterator() {
+    return new Iterator<Integer>() {
+      INode cursor = ListSnap.this.first.getNext();
+      public boolean hasNext() {
+        return cursor.getNext().getValue() == Integer.MAX_VALUE;
+      }
+      public Integer next() {
+        INode node = cursor;
+        cursor = cursor.getNext();
+        return node.getValue();
+      }
+      public void remove() {
+        throw new UnsupportedOperationException();
+      }
+      
+    };
+  }
+  protected class Neighborhood {
+    public INode prev;
+    public INode curr;
+    public Neighborhood(INode prev, INode curr) {
+      this.prev = prev;
+      this.curr = curr;
+    }
+    public Neighborhood(INode prev) {
+      this.prev = prev;
+    }
+  }
+  
+  @atomic public interface INode {
+    int getValue();
+    void setValue(int value);
+    INode getNext();
+    void setNext(INode value);
+  }
+
+    public Thread createThread(int which) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+}
+
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/Main.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/Main.java
new file mode 100644 (file)
index 0000000..ae0e771
--- /dev/null
@@ -0,0 +1,173 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+package dstm2.benchmark;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.util.logging.Level;
+import dstm2.Thread;
+import dstm2.Defaults;
+import java.io.File;
+
+
+/**
+ *
+ * @author navid
+ */
+public class Main {
+
+    /**
+     * @param args the command line arguments
+     * The first args is the name of the output file args[0]
+     * The second args is the name of the randomwords input file args[1]
+     * The third args is the name of the sequential words input file args[2]
+     */
+    public static void main(String[] args) {
+        
+        // Code For Inserting Words From Random File to The Binary Tree
+        
+    int numThreads = 20;//THREADS;
+    int numMillis  = Defaults.TIME;
+    int experiment = Defaults.EXPERIMENT;
+    String managerClassName = Defaults.MANAGER;
+    Class managerClass = null;
+    String benchmarkClassName = null;
+    Class benchmarkClass = null;
+    double ii = (double)new File("/home/navid/iliad.text").length() / (double)20;
+    
+    System.out.println(Math.ceil(ii));
+    String adapterClassName = Defaults.ADAPTER;
+    
+    // discard statistics from previous runs
+    Thread.clear();
+    // Parse and check the args
+    int argc = 0;
+    try {
+      while (argc < args.length) {
+        String option = args[argc++];
+        if (option.equals("-m"))
+          managerClassName = args[argc];
+        else if (option.equals("-b"))
+          benchmarkClassName = args[argc];
+        else if (option.equals("-t"))
+          numThreads = Integer.parseInt(args[argc]);
+        else if (option.equals("-n"))
+          numMillis = Integer.parseInt(args[argc]);
+        else if (option.equals("-e"))
+          experiment = Integer.parseInt(args[argc]);
+        else if (option.equals("-a"))
+          adapterClassName = args[argc];
+        else
+          reportUsageErrorAndDie();
+        argc++;
+      }
+    } catch (NumberFormatException e) {
+      System.out.println("Expected a number: " + args[argc]);
+      System.exit(0);
+    } catch (Exception e) {
+      reportUsageErrorAndDie();
+    }
+    
+    // Initialize contention manager.
+    try {
+      managerClass = Class.forName(Defaults.MANAGER);
+      Thread.setContentionManagerClass(managerClass);
+    } catch (ClassNotFoundException ex) {
+      reportUsageErrorAndDie();
+    }
+    
+    // Initialize adapter class
+    Thread.setAdapterClass(adapterClassName);
+    
+    // initialize benchmark
+    Benchmark benchmark = null;
+    try {
+      benchmarkClass = Class.forName(benchmarkClassName);
+      benchmark = (Benchmark) benchmarkClass.newInstance();
+      
+    } catch (InstantiationException e) {
+      System.out.format("%s does not implement dstm.benchmark.Benchmark: %s\n", benchmarkClass, e);
+      System.exit(0);
+    } catch (ClassCastException e) {
+      System.out.format("Exception when creating class %s: %s\n", benchmarkClass, e);
+      System.exit(0);
+    } catch (Exception e) {
+      e.printStackTrace(System.out);
+      System.exit(0);
+    }
+    
+    // Set up the benchmark
+    long startTime = 0;
+    
+    Thread[] thread = new Thread[numThreads];
+    System.out.println("Benchmark: " + benchmarkClass);
+    System.out.println("Adapter: " + adapterClassName);
+    System.out.println("Contention manager: " + managerClassName);
+    System.out.println("Threads: " + numThreads);
+    System.out.println("Mix: " + experiment + "% updates");
+    
+    
+        TransactionalIO.benchmarks.benchmark.init();
+    
+   // System.out.println((char)97);
+    int j = 97;
+    try {
+        for (int i = 0; i < numThreads; i++){
+             
+            //thread[i] = benchmark.createThread(experiment, (char)j);
+            thread[i] = benchmark.createThread(experiment, (char)j);
+            j++;
+        }
+      
+      startTime = System.currentTimeMillis();
+      for (int i = 0; i < numThreads; i++)
+        thread[i].start();
+     // Thread.sleep(numMillis);
+    //  Thread.stop = true;     // notify threads to stop
+      for (int i = 0; i < numThreads; i++) {
+        thread[i].join();
+      }
+    } catch (Exception e) {
+      e.printStackTrace(System.out);
+      System.exit(0);
+    }
+    long stopTime = System.currentTimeMillis();
+    
+    double elapsed = (double)(stopTime - startTime) / 1000.0;
+    
+    // Run the sanity check for this benchmark
+    try {
+      benchmark.sanityCheck();
+    } catch (Exception e) {
+      e.printStackTrace(System.out);
+    }
+    
+    long committed = Thread.totalCommitted;
+    long total = Thread.totalTotal;
+    if (total > 0) {
+      System.out.printf("Committed: %d\nTotal: %d\nPercent committed: (%d%%)\n",
+          committed,
+          total,
+          (100 * committed) / total);
+    } else {
+      System.out.println("No transactions executed!");
+    }
+    benchmark.report();
+    System.out.println("Elapsed time: " + elapsed + " seconds.");
+    System.out.println("------------------------------------------");
+    
+  
+  
+        
+    }
+      private static void reportUsageErrorAndDie() {
+    System.out.println("usage: dstm2.Main -b <benchmarkclass> [-m <managerclass>] [-t <#threads>] [-n <#time-in-ms>] [-e <experiment#>] [-a <adapter>]");
+    System.exit(0);
+  }
+
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/Main_for_Book_BenchMArk.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/Main_for_Book_BenchMArk.java
new file mode 100644 (file)
index 0000000..844b7be
--- /dev/null
@@ -0,0 +1,175 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import dstm2.Defaults;
+import dstm2.Thread;
+
+/**
+ *
+ * @author navid
+ */
+public class Main_for_Book_BenchMArk {
+    public static void main(String args[]){
+           // Code For Inserting Words From Random File to The Binary Tree
+    int numThreads = 2;//THREADS;
+    int numMillis  = Defaults.TIME;
+    int experiment = Defaults.EXPERIMENT;
+    String managerClassName =  null;// = Defaults.MANAGER;
+    Class managerClass = null;
+    String benchmarkClassName = null;
+    Class benchmarkClass = null;
+
+    
+    String adapterClassName = Defaults.ADAPTER;
+    
+    // discard statistics from previous runs
+    Thread.clear();
+    // Parse and check the args
+    int argc = 0;
+    try {
+      while (argc < args.length) {
+        String option = args[argc++];
+        if (option.equals("-m")){
+          managerClassName = args[argc];
+        }
+        else if (option.equals("-b")){
+          benchmarkClassName = args[argc];
+        }
+        else if (option.equals("-t"))
+          numThreads = Integer.parseInt(args[argc]);
+        else if (option.equals("-n"))
+          numMillis = Integer.parseInt(args[argc]);
+        else if (option.equals("-e"))
+          experiment = Integer.parseInt(args[argc]);
+        else if (option.equals("-a"))
+          adapterClassName = args[argc];
+        else
+          reportUsageErrorAndDie();
+        argc++;
+      }
+    } catch (NumberFormatException e) {
+      System.out.println("Expected a number: " + args[argc]);
+      System.exit(0);
+    } catch (Exception e) {
+      reportUsageErrorAndDie();
+    }
+    
+    // Initialize contention manager.
+    try {
+       System.out.println(managerClassName);    
+      managerClass = Class.forName(managerClassName);
+            System.out.println(managerClass);    
+      Thread.setContentionManagerClass(managerClass);
+    } catch (ClassNotFoundException ex) {
+      reportUsageErrorAndDie();
+    }
+    
+    // Initialize adapter class
+    Thread.setAdapterClass(adapterClassName);
+    
+    // initialize benchmark
+
+    TransactionalIO.benchmarks.benchmark.init();
+    CustomBenchmark benchmark = null;
+    try {
+      benchmarkClass = Class.forName(benchmarkClassName);
+      benchmark = (CustomBenchmark) benchmarkClass.newInstance();
+      
+    } catch (InstantiationException e) {
+      System.out.format("%s does not implement dstm.benchmark.Benchmark: %s\n", benchmarkClass, e);
+      System.exit(0);
+    } catch (ClassCastException e) {
+      System.out.format("Exception when creating class %s: %s\n", benchmarkClass, e);
+      System.exit(0);
+    } catch (Exception e) {
+      e.printStackTrace(System.out);
+      System.exit(0);
+    }
+    
+    // Set up the benchmark
+    long startTime = 0;
+    
+    CustomThread[] thread = new CustomThread[numThreads];
+    System.out.println("Benchmark: " + benchmarkClass);
+    System.out.println("Adapter: " + adapterClassName);
+    System.out.println("Contention manager: " + managerClassName);
+    System.out.println("Threads: " + numThreads);
+    System.out.println("Mix: " + experiment + "% updates");
+   // TransactionalIO.benchmarks.benchmark.init();
+    
+  
+  //  for(int k=0 ; k<400; k++){
+    
+    
+   // System.out.println((char)97);
+    int j = 97;
+    try {
+       for (int i = 0; i < numThreads; i++){
+             
+            //thread[i] = benchmark.createThread(experiment, (char)j);
+           
+            thread[i] = new CustomThread(benchmark);
+            j++;
+       }
+      
+       startTime = System.currentTimeMillis();
+       for (int i = 0; i < numThreads; i++)
+            thread[i].start();
+     // Thread.sleep(numMillis);
+    //  Thread.stop = true;     // notify threads to stop
+       for (int i = 0; i < numThreads; i++) {
+            thread[i].join();
+       }
+       
+    } catch (Exception e) {
+      e.printStackTrace(System.out);
+      System.exit(0);
+    }
+    long stopTime = System.currentTimeMillis();
+    
+    double elapsed = (double)(stopTime - startTime) / 1000.0;
+    
+    // Run the sanity check for this benchmark
+    try {
+      benchmark.sanityCheck();
+    } catch (Exception e) {
+      e.printStackTrace(System.out);
+    }
+    
+    long committed = Thread.totalCommitted;
+    long total = Thread.totalTotal;
+    if (total > 0) {
+      System.out.printf("Committed: %d\nTotal: %d\nPercent committed: (%d%%)\n",
+          committed,
+          total,
+          (100 * committed) / total);
+    } else {
+      System.out.println("No transactions executed!");
+    }
+    benchmark.report();
+    System.out.println("Elapsed time: " + elapsed + " seconds.");
+    System.out.println("------------------------------------------");
+    
+   /* BufferedReader dataIn = new BufferedReader(new
+                InputStreamReader( System.in) );
+      
+    String name = "";
+    try{
+    name = dataIn.readLine();
+        }catch( IOException e ){
+            System.out.println("Error!");
+        }*/
+ //   }
+  //  benchmark.printResults();
+        
+    }
+    private static void reportUsageErrorAndDie() {
+        System.out.println("usage: dstm2.Main -b <benchmarkclass> [-m <managerclass>] [-t <#threads>] [-n <#time-in-ms>] [-e <experiment#>] [-a <adapter>]");
+        System.exit(0); 
+    }
+
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/PureIO.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/PureIO.java
new file mode 100644 (file)
index 0000000..da43127
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.TransactionalFile;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.Vector;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ *
+ * @author navid
+ */
+public class PureIO extends CustomBenchmark {
+
+    @Override
+    protected void init() {
+        
+    }
+
+    
+    protected void execute(Vector arguments) {
+            char[] holder = (char[]) arguments.get(0);
+            int i = ((Integer) (arguments.get(1))).intValue();
+            byte[] towrite = (byte[]) arguments.get(2);
+        try {
+            
+              ((TransactionalFile) (benchmark.m.get(String.valueOf(holder,0,i).toLowerCase().substring(0, 1)))).write(towrite);         
+            //  ((RandomAccessFile) (benchmark.m.get(String.valueOf(holder,0,i).toLowerCase().substring(0, 1)))).write(towrite);         
+   //           
+        } catch (NullPointerException e){
+             System.out.println(i);
+             System.out.println(holder[0]);
+             System.out.println("kir " + String.valueOf(holder,0,i).toLowerCase().substring(0, 1));
+             
+        
+        } catch (IOException ex) {
+            Logger.getLogger(PureIO.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        
+    }
+
+    
+    protected void printResults() {
+        
+    }
+
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/PureIOdstm2version.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/PureIOdstm2version.java
new file mode 100644 (file)
index 0000000..7050c9e
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.TransactionalFile;
+import dstm2.SpecialTransactionalFile;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.HashMap;
+import java.util.Vector;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ *
+ * @author navid
+ */
+public class PureIOdstm2version extends CustomBenchmark {
+
+    
+    
+    int count = 0;
+    @Override
+    protected void init() {
+         int index = 97;
+            
+            for (int i = 0; i < 26; i++) { 
+                try {
+                    benchmark.m.put(String.valueOf((char) (index + i) +"special"), new SpecialTransactionalFile("/scratch/TransactionalIO/PureIOBenchmarkFiles/" + String.valueOf((char) (index + i)) + ".text", "rw"));
+                    //System.out.println(String.valueOf((char) (index + i) +"special"));
+                } catch (FileNotFoundException ex) {
+                    Logger.getLogger(PureIOdstm2version.class.getName()).log(Level.SEVERE, null, ex);
+                }
+                    count++;
+            }   
+    }
+
+    
+    protected void execute(Vector arguments) {
+            char[] holder = (char[]) arguments.get(0);
+            int i = ((Integer) (arguments.get(1))).intValue();
+            byte[] towrite = (byte[]) arguments.get(2);
+        try {
+            
+             // ((TransactionalFile) (benchmark.m.get(String.valueOf(holder,0,i).toLowerCase().substring(0, 1)))).write(towrite);         
+            //System.out.println(((SpecialTransactionalFile) (benchmark.m.get(String.valueOf(holder,0,i).toLowerCase().substring(0, 1)+"special"))));
+             ((SpecialTransactionalFile) (benchmark.m.get(String.valueOf(holder,0,i).toLowerCase().substring(0, 1)+"special"))).write(towrite);         
+   //           
+        } catch (NullPointerException e){
+             System.out.println(String.valueOf(holder,0,i).toLowerCase().substring(0, 1)+"special");
+             
+        
+        } catch (IOException ex) {
+            Logger.getLogger(PureIO.class.getName()).log(Level.SEVERE, null, ex);
+        }
+        
+    }
+
+    
+    protected void printResults() {
+        
+    }
+
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/PureIOtest.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/PureIOtest.java
new file mode 100644 (file)
index 0000000..ba29f6e
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * To change this template, choose Tools | Templates
+ * and open the template in the editor.
+ */
+
+package dstm2.benchmark;
+
+import TransactionalIO.benchmarks.benchmark;
+import TransactionalIO.core.TransactionalFile;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.util.Vector;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ *
+ * @author navid
+ */
+public class PureIOtest extends CustomBenchmark{
+
+    @Override
+    protected void init() {
+        
+    }
+
+
+    protected void execute() {
+        try {
+            TransactionalFile f1 = (TransactionalFile)benchmark.m.get("0");
+           // RandomAccessFile f1 = ((TransactionalFile) benchmark.m.get("0")).file;
+            byte[] data = new byte[1];
+            char[] holder = new char[10000];
+            char[] word = new char[20];
+            boolean flag = false;
+            long toseek = Integer.valueOf(Thread.currentThread().getName().substring(7)) * 20448;
+
+          //  benchmark.filelock.lock();
+            f1.seek(toseek);
+
+            data[0] = 'a';
+            if (toseek != 0) {
+                //////////////// skipt the first word since its been read already
+                while (data[0] != '\n') {
+                    int res;
+                    res = f1.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+                }
+            }
+            while (f1.getFilePointer() < toseek + 20448) {
+                if (flag == true) {
+                    break;
+                }
+                data[0] = 'a';
+                int i = 0;
+                int res;
+                while (data[0] != '\n') {
+                    res = f1.read(data);
+                    if (res == -1) {
+                        flag = true;
+                        break;
+                    }
+
+                    holder[i] = (char) data[0];
+                    i++;
+                }
+
+
+                byte[] towrite = new byte[String.valueOf(holder, 0, i).length()];
+                towrite = String.valueOf(holder, 0, i).getBytes();
+
+
+
+                  //     System.out.println(String.valueOf(holder,0,i).toLowerCase().substring(0, 1));
+                    //((TransactionalFile) (benchmark.m.get(String.valueOf(holder,0,i).toLowerCase().substring(0, 1)))).file.write(towrite);
+                ((TransactionalFile) (benchmark.m.get(String.valueOf(holder,0,i).toLowerCase().substring(0, 1)))).write(towrite);
+                    //update the memory         //}
+            }
+           // benchmark.filelock.unlock();
+        } catch (IOException ex) {
+            Logger.getLogger(PureIOtest.class.getName()).log(Level.SEVERE, null, ex);
+        } catch (NullPointerException e) {
+            e.printStackTrace();
+        }
+    }
+
+    @Override
+    protected void printResults() {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+    @Override
+    protected void execute(Vector arguments) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/RBTree.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/RBTree.java
new file mode 100644 (file)
index 0000000..6b73e08
--- /dev/null
@@ -0,0 +1,649 @@
+/*
+ * RBTree.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa
+ * Clara, California 95054, U.S.A.  All rights reserved.  
+ * 
+ * Sun Microsystems, Inc. has intellectual property rights relating to
+ * technology embodied in the product that is described in this
+ * document.  In particular, and without limitation, these
+ * intellectual property rights may include one or more of the
+ * U.S. patents listed at http://www.sun.com/patents and one or more
+ * additional patents or pending patent applications in the U.S. and
+ * in other countries.
+ * 
+ * U.S. Government Rights - Commercial software.
+ * Government users are subject to the Sun Microsystems, Inc. standard
+ * license agreement and applicable provisions of the FAR and its
+ * supplements.  Use is subject to license terms.  Sun, Sun
+ * Microsystems, the Sun logo and Java are trademarks or registered
+ * trademarks of Sun Microsystems, Inc. in the U.S. and other
+ * countries.  
+ * 
+ * This product is covered and controlled by U.S. Export Control laws
+ * and may be subject to the export or import laws in other countries.
+ * Nuclear, missile, chemical biological weapons or nuclear maritime
+ * end uses or end users, whether direct or indirect, are strictly
+ * prohibited.  Export or reexport to countries subject to
+ * U.S. embargo or to entities identified on U.S. export exclusion
+ * lists, including, but not limited to, the denied persons and
+ * specially designated nationals lists is strictly prohibited.
+ */
+
+package dstm2.benchmark;
+
+import dstm2.atomic;
+import dstm2.benchmark.Benchmark;
+import dstm2.factory.Factory;
+import dstm2.Thread;
+import java.util.EmptyStackException;
+import java.util.Iterator;
+import java.util.Stack;
+
+/**
+ * Red-Black tree benchmark.
+ * Adapted from {@link http://www.codeproject.com/csharp/RedBlackCS.asp
+ * }
+ * @author Maurice Herlihy
+ */
+public class RBTree extends IntSetBenchmark {
+  /**
+   * Transactional RBNode factory.
+   */
+  static Factory<RBNode> factory = Thread.makeFactory(RBNode.class);
+  /**
+   * Each node has one of two colors.
+   */
+  public enum Color {BLACK, RED};
+  
+  /**
+   * Left hand of darkness: the actual root of the tree is the left-hand
+   * child of this node. Indirection needed to make changes to the root
+   * transactional.
+   */
+  private RBNode root;
+  /**
+   * Used in place of null pointer.
+   */
+  public static RBNode sentinelNode;  
+  /**
+   * Initializes the tree shared by all the threads.
+   **/
+  public void init() {
+    sentinelNode = factory.create();
+    sentinelNode.setLeft(null);
+    sentinelNode.setRight(null);
+    sentinelNode.setParent(null);
+    sentinelNode.setColor(Color.BLACK);
+    root = factory.create();
+    root.setLeft(sentinelNode);
+    this.root.setValue(Integer.MIN_VALUE);
+    this.root.setColor(Color.BLACK);
+    int size = 0;
+  }
+  
+  protected RBNode getRoot() {
+    return root.getLeft();
+  }
+  
+  protected void setRoot(RBNode value) {
+    root.setLeft(value);
+  }
+  
+  /**
+   * Inserts an element into the tree, if it is not already present.
+   * @param key element to insert
+   * @return true iff item was not there already
+   */
+  public boolean insert(int key) {
+    // traverse tree - find where node belongs
+    RBNode node        = factory.create();
+    RBNode temp        = getRoot();
+    
+    while(temp != sentinelNode) {      // find Parent
+      node.setParent(temp);
+      if ( key == temp.getValue()) {
+        return false;
+      } else if (key > temp.getValue()) {
+        temp = temp.getRight();
+      } else {
+        temp = temp.getLeft();
+      }
+    }
+    
+    // setup node
+    node.setValue(key);
+    node.setLeft(sentinelNode);
+    node.setRight(sentinelNode);
+    
+    // insert node into tree starting at parent's location
+    if(node.getParent() != null) {
+      if (node.getValue() > node.getParent().getValue()) {
+        node.getParent().setRight(node);
+      } else
+        node.getParent().setLeft(node);
+    } else
+      setRoot(node);           // first node added
+    
+    restoreAfterInsert(node);           // restore red-black properities
+    return true;
+  }
+  
+  /**
+   * Tests whether item is present.
+   * @return whether the item was present</returns>
+   * @param key item to search for
+   */
+  public boolean contains(int key) {
+    
+    RBNode node = getRoot();     // begin at root
+    
+    // traverse tree until node is found
+    while(node != sentinelNode) {
+      if (key == node.getValue()) {
+        return true;
+      } else if (key < node.getValue()) {
+        node = node.getLeft();
+      } else {
+        node = node.getRight();
+      }
+    }
+    return false;
+  }
+  
+  /**
+   * Remove item if present.
+   * @return whether the item was removed</returns>
+   * @param key item to remove
+   */
+  public boolean remove(int key) {
+    
+    // find node
+    RBNode node;
+    
+    node = getRoot();
+    while(node != sentinelNode) {
+      if (key == node.getValue()) {
+        break;
+      } else if (key < node.getValue()) {
+        node = node.getLeft();
+      } else {
+        node = node.getRight();
+      }
+    }
+    
+    if(node == sentinelNode)
+      return false;                            // key not found
+    
+    delete(node);
+    return true;
+  }
+  
+  /**
+   * Delete a node.
+   * A node to be deleted will be:
+   *           1. a leaf with no children
+   *           2. have one child
+   *           3. have two children
+   * If the deleted node is red, the red black properties still hold.
+   * If the deleted node is black, the tree needs rebalancing
+   * @param z start at this node
+   */
+  private void delete(RBNode z) {
+    
+    RBNode x = factory.create();       // work node to contain the replacement node
+    RBNode y;                                  // work node
+    
+    // find the replacement node (the successor to x) - the node one with
+    // at *most* one child.
+    if(z.getLeft() == sentinelNode || z.getRight() == sentinelNode)
+      y = z;                                           // node has sentinel as a child
+    else {
+      // z has two children, find replacement node which will
+      // be the leftmost node greater than z
+      y = z.getRight();                                        // traverse right subtree
+      while(y.getLeft() != sentinelNode)               // to find next node in sequence
+        y = y.getLeft();
+    }
+    
+    // at this point, y contains the replacement node. it's content will be copied
+    // to the valules in the node to be deleted
+    
+    // x (y's only child) is the node that will be linked to y's old parent.
+    if(y.getLeft() != sentinelNode)
+      x = y.getLeft();
+    else
+      x = y.getRight();
+    
+    // replace x's parent with y's parent and
+    // link x to proper subtree in parent
+    // this removes y from the chain
+    x.setParent(y.getParent());
+    if(y.getParent() != null)
+      if(y == y.getParent().getLeft())
+        y.getParent().setLeft(x);
+      else
+        y.getParent().setRight(x);
+    else
+      setRoot(x);              // make x the root node
+    
+    // copy the values from y (the replacement node) to the node being deleted.
+    // note: this effectively deletes the node.
+    if(y != z) {
+      z.setValue(y.getValue());
+    }
+    
+    if(y.getColor() == Color.BLACK)
+      restoreAfterDelete(x);
+  }
+  
+  /**
+   * restoreAfterDelete
+   * Deletions from red-black trees may destroy the red-black
+   * properties. Examine the tree and restore. Rotations are normally
+   * required to restore it
+   * @param x start here
+   */
+  private void restoreAfterDelete(RBNode x) {
+    // maintain Red-Black tree balance after deleting node
+    
+    RBNode y;
+    
+    while(x != getRoot() && x.getColor() == Color.BLACK) {
+      if(x == x.getParent().getLeft())                 // determine sub tree from parent
+      {
+        y = x.getParent().getRight();                  // y is x's sibling
+        if(y.getColor() == Color.RED) {        // x is black, y is red - make both black and rotate
+          y.setColor(Color.BLACK);
+          x.getParent().setColor(Color.RED);
+          rotateLeft(x.getParent());
+          y = x.getParent().getRight();
+        }
+        if(y.getLeft().getColor() == Color.BLACK &&
+            y.getRight().getColor() == Color.BLACK) {  // children are both black
+          y.setColor(Color.RED); // change parent to red
+          x = x.getParent(); // move up the tree
+        } else {
+          if(y.getRight().getColor() == Color.BLACK) {
+            y.getLeft().setColor(Color.BLACK);
+            y.setColor(Color.RED);
+            rotateRight(y);
+            y                          = x.getParent().getRight();
+          }
+          y.setColor(x.getParent().getColor());
+          x.getParent().setColor(Color.BLACK);
+          y.getRight().setColor(Color.BLACK);
+          rotateLeft(x.getParent());
+          setRoot(x);
+        }
+      } else { // right subtree - same as code above with right and left swapped
+        y = x.getParent().getLeft();
+        if(y.getColor() == Color.RED) {
+          y.setColor(Color.BLACK);
+          x.getParent().setColor(Color.RED);
+          rotateRight(x.getParent());
+          y = x.getParent().getLeft();
+        }
+        if(y.getRight().getColor() == Color.BLACK &&
+            y.getLeft().getColor() == Color.BLACK) {
+          y.setColor(Color.RED);
+          x            = x.getParent();
+        } else {
+          if(y.getLeft().getColor() == Color.BLACK) {
+            y.getRight().setColor(Color.BLACK);
+            y.setColor(Color.RED);
+            rotateLeft(y);
+            y                          = x.getParent().getLeft();
+          }
+          y.setColor(x.getParent().getColor());
+          x.getParent().setColor(Color.BLACK);
+          y.getLeft().setColor(Color.BLACK);
+          rotateRight(x.getParent());
+          setRoot(x);
+        }
+      }
+    }
+    x.setColor(Color.BLACK);
+  }
+  
+  /**
+   * Insertions may destroy the red-black  properties. Examine the tree
+   * and rotate as needed to restore the property.
+   * @param x start here
+   */
+  private void restoreAfterInsert(RBNode x) {
+    RBNode y;
+    
+    // maintain red-black tree properties after adding x
+    while(x != getRoot() && x.getParent().getColor() == Color.RED) {
+      // Parent node is .Colored red;
+      if(x.getParent() == x.getParent().getParent().getLeft()) // determine traversal path
+      {                                                                                // is it on the Left or Right subtree?
+        y = x.getParent().getParent().getRight();                      // get uncle
+        if(y!= null && y.getColor() == Color.RED) {    // uncle is red; change x's Parent and uncle to black
+          x.getParent().setColor(Color.BLACK);
+          y.setColor(Color.BLACK);
+          // grandparent must be red. Why? Every red node that is not
+          // a leaf has only black children
+          x.getParent().getParent().setColor(Color.RED);
+          x                                            = x.getParent().getParent();    // continue loop with grandparent
+        } else {
+          // uncle is black; determine if x is greater than Parent
+          if(x == x.getParent().getRight()) {  // yes, x is greater than Parent; rotate Left
+            // make x a Left child
+            x = x.getParent();
+            rotateLeft(x);
+          }
+          // no, x is less than Parent
+          x.getParent().setColor(Color.BLACK); // make Parent black
+          x.getParent().getParent().setColor(Color.RED);               // make grandparent black
+          rotateRight(x.getParent().getParent());                                      // rotate right
+        }
+      } else { // x's Parent is on the Right subtree
+        // this code is the same as above with "Left" and "Right" swapped
+        y = x.getParent().getParent().getLeft();
+        if(y!= null && y.getColor() == Color.RED) {
+          x.getParent().setColor(Color.BLACK);
+          y.setColor(Color.BLACK);
+          x.getParent().getParent().setColor(Color.RED);
+          x                                            = x.getParent().getParent();
+        } else {
+          if(x == x.getParent().getLeft()) {
+            x = x.getParent();
+            rotateRight(x);
+          }
+          x.getParent().setColor(Color.BLACK);
+          x.getParent().getParent().setColor(Color.RED);
+          rotateLeft(x.getParent().getParent());
+        }
+      }
+    }
+    getRoot().setColor(Color.BLACK);           // root should always be black
+  }
+  
+  /**
+   * rotateLeft
+   * Rebalance the tree by rotating the nodes to the left
+   * @param x start here
+   */
+  public void rotateLeft(RBNode x) {
+    // pushing node x down and to the Left to balance the tree. x's Right child (y)
+    // replaces x (since y > x), and y's Left child becomes x's Right child
+    // (since it's < y but > x).
+    
+    RBNode y = x.getRight(); // get x's Right node, this becomes y
+    
+    // set x's Right link
+    x.setRight(y.getLeft());   // y's Left child's becomes x's Right child
+    
+    // modify parents
+    if(y.getLeft() != sentinelNode)
+      y.getLeft().setParent(x);                // sets y's Left Parent to x
+    
+    if(y != sentinelNode)
+      y.setParent(x.getParent());      // set y's Parent to x's Parent
+    
+    if(x.getParent() != null) {        // determine which side of it's Parent x was on
+      if(x == x.getParent().getLeft())
+        x.getParent().setLeft(y);                      // set Left Parent to y
+      else
+        x.getParent().setRight(y);                     // set Right Parent to y
+    } else
+      setRoot(y);                                              // at root, set it to y
+    
+    // link x and y
+    y.setLeft(x);                      // put x on y's Left
+    if(x != sentinelNode)              // set y as x's Parent
+      x.setParent(y);
+  }
+  
+  /**
+   * rotateRight
+   * Rebalance the tree by rotating the nodes to the right
+   * @param x start here
+   */
+  public void rotateRight(RBNode x) {
+    // pushing node x down and to the Right to balance the tree. x's Left child (y)
+    // replaces x (since x < y), and y's Right child becomes x's Left child
+    // (since it's < x but > y).
+    
+    RBNode y = x.getLeft();                    // get x's Left node, this becomes y
+    
+    // set x's Right link
+    x.setLeft(y.getRight());                   // y's Right child becomes x's Left child
+    
+    // modify parents
+    if(y.getRight() != sentinelNode)
+      y.getRight().setParent(x);               // sets y's Right Parent to x
+    
+    if(y != sentinelNode)
+      y.setParent(x.getParent());                      // set y's Parent to x's Parent
+    
+    if(x.getParent() != null)                          // null=root, could also have used root
+    {  // determine which side of its Parent x was on
+      if(x == x.getParent().getRight())
+        x.getParent().setRight(y);                     // set Right Parent to y
+      else
+        x.getParent().setLeft(y);                      // set Left Parent to y
+    } else
+      setRoot(y);                                              // at root, set it to y
+    
+    // link x and y
+    y.setRight(x);                                     // put x on y's Right
+    if(x != sentinelNode)                              // set y as x's Parent
+      x.setParent(y);
+  }
+  
+  /**
+   * returns number of black nodes akibg root to leaf path
+   * @param root tree root
+   * @return number of black nodes in left-most path
+   */
+  private int countBlackNodes(RBNode root) {
+    if (sentinelNode == root)
+      return 0;
+    int me = (root.getColor() == Color.BLACK) ? 1 : 0;
+    RBNode left = (sentinelNode == root.getLeft())
+    ? sentinelNode
+        : root.getLeft();
+    return me + countBlackNodes(left);
+  }
+  
+  /**
+   * counts nodes in tree
+   * @param root tree root
+   * @return number of nodes in tree
+   */
+  private int count(RBNode root) {
+    if (root == sentinelNode)
+      return 0;
+    return 1 + count(root.getLeft()) + count(root.getRight());
+  }
+  
+  /**
+   * Checks internal consistency.
+   * @param root tree root
+   * @param blackNodes number of black nodes expected in leaf-to-root path
+   * @param soFar number of black nodes seen in path so far
+   */
+  private void recursiveValidate(RBNode root, int blackNodes, int soFar) {
+    // Empty sub-tree is vacuously OK
+    if (sentinelNode == root)
+      return;
+    
+    Color rootcolor = root.getColor();
+    soFar += ((Color.BLACK == rootcolor) ? 1 : 0);
+    root.setMarked(true);
+    
+    // Check left side
+    RBNode left = root.getLeft();
+    if (sentinelNode != left) {
+      if (left.getColor() != Color.RED || rootcolor != Color.RED) {
+        System.out.println("Error: Two consecutive red nodes!");
+      }
+      if (left.getValue() < root.getValue()) {
+        System.out.println(" Error; Tree values out of order!");
+      }
+      if (!left.isMarked()) {
+        System.out.println("Error; Cycle in tree structure!");
+      }
+      recursiveValidate(left, blackNodes, soFar);
+    }
+    
+    // Check right side
+    RBNode right = root.getRight();
+    if (sentinelNode != right) {
+      if (right.getColor() != Color.RED || rootcolor != Color.RED) {
+        System.out.println("Error: Two consecutive red nodes!");
+      }
+      if (right.getValue() > root.getValue()) {
+        System.out.println("Error: Tree values out of order!");
+      }
+      if (!right.isMarked()) {
+        System.out.println("Error: Cycle in tree structure!");
+      }
+      recursiveValidate(right, blackNodes, soFar);
+    }
+    
+    // Check black node count
+    if (sentinelNode == root.getLeft() || sentinelNode == root.getRight()) {
+      if (soFar != blackNodes) {
+        System.out.println("Error: Variable number of black nodes to leaves!");
+        return;
+      }
+    }
+    // Everything checks out if we get this far.
+    return;
+  }
+  
+  public Iterator<Integer> iterator() {
+    return new MyIterator();
+  }
+  
+  /**
+   * Tree node definition. Implemented by transactional factory.
+   */
+  @atomic public interface RBNode {
+    
+    /**
+     * Reads node value.
+     * @return node value
+     */
+    public int getValue();
+    
+    /**
+     * sets node value
+     * @param newValue new value for node
+     */
+    public void setValue(int newValue);
+    
+    /**
+     * is node marked?
+     * @return whether node is marked
+     */
+    public boolean isMarked();
+    
+    /**
+     * mark or unmark node
+     * @param newMarked new value for marked flag
+     */
+    public void setMarked(boolean newMarked);
+    
+    /**
+     * examine node color
+     * @return node color
+     */
+    public Color getColor();
+    
+    /**
+     * change node's color
+     * @param newColor new color
+     */
+    public void setColor(Color newColor);
+    
+    /**
+     * examine node's parent
+     * @return node's parent
+     */
+    public RBNode getParent();
+    
+    /**
+     * change node's parent
+     * @param newParent new parent
+     */
+    public void setParent(RBNode newParent);
+    
+    /**
+     * examine node's left child
+     * @return node's left child
+     */
+    public RBNode getLeft();
+    
+    /**
+     * change node's right child
+     * @param newLeft new left child
+     */
+    public void setLeft(RBNode newLeft);
+    
+    /**
+     * examine node's right child
+     * @return node's right child
+     */
+    public RBNode getRight();
+    
+    /**
+     * change node's left child
+     * @param newRight new right child
+     */
+    public void setRight(RBNode newRight);
+    
+  }
+  
+  private class MyIterator implements Iterator<Integer> {
+    RBNode node = getRoot();
+    RBNode prev = node;
+    RBNode next = node;
+    Stack<RBNode> stack = new Stack<RBNode>();
+    MyIterator() {
+      while (node != sentinelNode) {
+        stack.push(node);
+        node = node.getLeft();
+      }
+      next = prev = stack.peek();
+    }
+    public boolean hasNext() {
+      return !stack.empty();
+    }
+    public void remove() {
+      throw new UnsupportedOperationException();
+    }
+    public Integer next() {
+      prev = next;
+      node = stack.peek();
+      // If I have a right child, move there and descend left
+      if (node.getRight() != sentinelNode) {
+        node = node.getRight();
+        while (node != sentinelNode) {
+          stack.push(node);
+          node = node.getLeft();
+        }
+      } else {
+        RBNode seen = sentinelNode;
+        while (node.getRight() == seen) {
+          seen = stack.pop();
+          if (stack.empty()) {
+            next = null;
+            break;
+          } else {
+            next = node = stack.peek();
+          }
+        }
+      }
+      return prev.getValue();
+    }
+  }
+
+    public Thread createThread(int which) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+}
diff --git a/Robust/Transactions/dstm2/src/dstm2/benchmark/SkipList.java b/Robust/Transactions/dstm2/src/dstm2/benchmark/SkipList.java
new file mode 100644 (file)
index 0000000..a3af586
--- /dev/null
@@ -0,0 +1,256 @@
+/*
+ * SkipList.java
+ *
+ * Copyright 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa
+ * Clara, California 95054, U.S.A.  All rights reserved.  
+ * 
+ * Sun Microsystems, Inc. has intellectual property rights relating to
+ * technology embodied in the product that is described in this
+ * document.  In particular, and without limitation, these
+ * intellectual property rights may include one or more of the
+ * U.S. patents listed at http://www.sun.com/patents and one or more
+ * additional patents or pending patent applications in the U.S. and
+ * in other countries.
+ * 
+ * U.S. Government Rights - Commercial software.
+ * Government users are subject to the Sun Microsystems, Inc. standard
+ * license agreement and applicable provisions of the FAR and its
+ * supplements.  Use is subject to license terms.  Sun, Sun
+ * Microsystems, the Sun logo and Java are trademarks or registered
+ * trademarks of Sun Microsystems, Inc. in the U.S. and other
+ * countries.  
+ * 
+ * This product is covered and controlled by U.S. Export Control laws
+ * and may be subject to the export or import laws in other countries.
+ * Nuclear, missile, chemical biological weapons or nuclear maritime
+ * end uses or end users, whether direct or indirect, are strictly
+ * prohibited.  Export or reexport to countries subject to
+ * U.S. embargo or to entities identified on U.S. export exclusion
+ * lists, including, but not limited to, the denied persons and
+ * specially designated nationals lists is strictly prohibited.
+ */
+
+package dstm2.benchmark;
+
+import dstm2.AtomicArray;
+import dstm2.atomic;
+import dstm2.factory.Factory;
+import dstm2.Thread;
+import dstm2.util.Random;
+import java.util.Iterator;
+
+/**
+ * @author Maurice Herlihy
+ */
+public class SkipList extends IntSetBenchmark {
+  /**
+   * Transactional Node factory.
+   */
+  static Factory<Node> factory = Thread.makeFactory(Node.class);
+  
+  // Maximum level any node in a skip list can have
+  private final int MaxLevel = 32;
+  
+  // Probability factor used to determine the node level
+  private final double Probability = 0.5;
+  
+  // The skip list header. It also serves as the NIL node.
+  private Node header;
+  
+  // Random number generator for generating random node levels.
+  private Random random;
+  
+  // Current maximum list level.
+  private int listLevel;
+  
+  protected void init() {
+    int size = 0;
+    header = factory.create();
+    random = new Random();
+    initNode(header, MaxLevel);
+    listLevel = 1;
+    AtomicArray<Node> forward = header.getForward();
+    for (int i = 0; i < MaxLevel; i++) {
+      forward.set(i, header);
+    }
+  }
+  
+  public java.util.Iterator<Integer> iterator() {
+    return new MyIterator();
+  }
+  
+  public boolean insert(int key) {
+    Node[] update = new Node[MaxLevel];
+    Node curr = search(key, update);
+    // If key does not already exist in the skip list.
+    if(curr.getKey() != key) {
+      insert(key, update);
+      return true;
+    } else {
+      return false;
+    }
+  }
+  
+  public boolean contains(int key) {
+    Node[] dummy = new Node[MaxLevel];
+    Node curr = search(key, dummy);
+    return curr.getKey() == key;
+  }
+  
+  public boolean remove(int key) {
+    Node[] update = new Node[MaxLevel];
+    Node curr = search(key, update);
+    if(curr.getKey() == key) {
+      // Redirect references to victim node to successors.
+      for (int i = 0; i < listLevel && update[i].getForward().get(i) == curr; i++) {
+        update[i].getForward().set(i, curr.getForward().get(i));
+      }
+      return true;
+    }
+    return false;
+  }
+  
+  private class MyIterator implements Iterator<Integer> {
+    Node node = header.getForward().get(0);
+    public boolean hasNext() {
+      return node != header;
+    }
+    public void remove() {
+      throw new UnsupportedOperationException();
+    }
+    public Integer next() {
+      node = node.getForward().get(0);
+      return node.getKey();
+    }
+  }
+  /**
+   * Initializes an instant of a Node with its node level.
+   **/
+  public void initNode(Node node, int level) {
+    node.setForward(new AtomicArray<Node>(Node.class, level));
+  }
+  
+  /**
+   * Initializes an instant of a Node with its node level and
+   * key/value pair.
+   **/
+  public void initNode(Node node, int level, int key) {
+    node.setForward(new AtomicArray<Node>(Node.class, level));
+    node.setKey(key);
+  }
+  
+  /// <summary>
+  /// Returns a level value for a new SkipList node.
+  /// <returns>
+  /// The level value for a new SkipList node.
+  /// </returns>
+  /// </summary>
+  private int getNewLevel() {
+    int level = 1;
+    while(random.nextDouble() < Probability && level < MaxLevel && level <= listLevel) {
+      level++;
+    }
+    return level;
+  }
+  
+  /// <summary>
+  /// Inserts a keykey into the SkipList.
+  /// <param name="key">
+  /// The key to insert into the SkipList.
+  /// </param>
+  /// <param name="update">
+  /// An array of nodes holding references to places in the SkipList in
+  /// which the search for the place to insert the new key/value pair
+  /// dropped down one level.
+  /// </param>
+  /// </summary>
+  private void insert(int key, Node[] update) {
+    // Get the level for the new node.
+    int newLevel = getNewLevel();
+    // If new node level greater than skip list level.
+    if (newLevel > listLevel) {
+      // Make sure our update references above the current skip list
+      // level point to the header.
+      for (int i = listLevel; i < newLevel; i++) {
+        update[i] = header;
+      }
+      // The current skip list level is now the new node level.
+      listLevel++;
+    }
+    // Create the new node.
+    Node newNode = factory.create();
+    initNode(newNode, newLevel, key);
+    // Insert the new node into the skip list.
+    for (int i = 0; i < newLevel; i++) {
+      // Initialize new node forward references to update forward references
+      newNode.getForward().set(i, update[i].getForward().get(i));
+      // Set update forward references to new node.
+      update[i].getForward().set(i, newNode);
+    }
+  }
+  
+  /// <summary>
+  /// Search for the specified key.
+  /// <param name="_key">
+  /// The key to search for.
+  /// </param>
+  /// <param name="curr">
+  /// A SkipList node to hold the results of the search.
+  /// </param>
+  /// <param name="update">
+  /// An array of nodes holding references to the places in the SkipList
+  /// search in which the search dropped down one level.
+  /// </param>
+  /// <returns>
+  /// Returns node with least key greater than or equal to search key.
+  /// </returns>
+  /// </summary>
+  private Node search(int key, Node[] update) {
+    int comp;
+    // Begin at the start of the skip list.
+    Node curr = header;
+    // Work our way down from the top of the skip list to the bottom.
+    for(int i = listLevel - 1; i >= 0; i--) {
+      comp = curr.getForward().get(i).getKey();
+      // While we haven't reached the end of the skip list and the
+      // current key is less than the search key.
+      while(curr.getForward().get(i) != header && comp < key) {
+        // Move forward in the skip list.
+        curr = curr.getForward().get(i);
+        // Get the current key.
+        comp = curr.getForward().get(i).getKey();
+      }
+      // Keep track of each node where we move down a level. Used later to rearrange
+      // node references when inserting a new element.
+      update[i] = curr;
+    }
+    // Move ahead in the skip list. If the key isn't there, we end up at a node with a
+    // key greater key, and otherwise at a node with the same key.
+    curr = curr.getForward().get(0);
+    return curr;
+  }
+  
+  @atomic public interface Node {
+    /**
+     * Get array of nodes further along in the skip list.
+     **/
+    public AtomicArray<Node> getForward();
+    /**
+     * Set array of nodes further along in the skip list.
+     **/
+    public void setForward(AtomicArray<Node> value);
+    
+    /**
+     * Get node value.
+     **/
+    public int getKey();
+    /**
+     * Set node value.
+     **/
+    public void setKey(int value);
+  }
+
+    public Thread createThread(int which) {
+        throw new UnsupportedOperationException("Not supported yet.");
+    }
+}