Package org.objectweb.speedo.runtime.tck

Source Code of org.objectweb.speedo.runtime.tck.PersistenceManagerTck$PMThread

/**
* Copyright (C) 2001-2004 France Telecom R&D
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
package org.objectweb.speedo.runtime.tck;

import org.objectweb.speedo.SpeedoTestHelper;
import org.objectweb.speedo.pobjects.basic.BasicA;
import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Properties;

import javax.jdo.JDOHelper;
import javax.jdo.JDOUserException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;

import junit.framework.Assert;

public class PersistenceManagerTck extends SpeedoTestHelper {

  public static final int TRANSIENT = 0;
  public static final int PERSISTENT_NEW = 1;
  public static final int PERSISTENT_CLEAN = 2;
  public static final int PERSISTENT_DIRTY = 3;
  public static final int HOLLOW = 4;
  public static final int TRANSIENT_CLEAN = 5;
  public static final int TRANSIENT_DIRTY = 6;
  public static final int PERSISTENT_NEW_DELETED = 7;
  public static final int PERSISTENT_DELETED = 8;
  public static final int PERSISTENT_NONTRANSACTIONAL = 9;
  public static final int NUM_STATES = 10;
  public static final int ILLEGAL_STATE = 10;

  public static final String[] states =
    {
      "transient",
      "persistent-new",
      "persistent-clean",
      "persistent-dirty",
      "hollow",
      "transient-clean",
      "transient-dirty",
      "persistent-new-deleted",
      "persistent-deleted",
      "persistent-nontransactional",
      "illegal" };

  private static final int IS_PERSISTENT = 0;
  private static final int IS_TRANSACTIONAL = 1;
  private static final int IS_DIRTY = 2;
  private static final int IS_NEW = 3;
  private static final int IS_DELETED = 4;
  private static final int NUM_STATUSES = 5;

  private static final boolean state_statuses[][] = {
    //      IS_PERSISTENT IS_TRANSACTIONAL IS_DIRTY IS_NEW IS_DELETED
    // transient
    { false, false, false, false, false },

    // persistent-new
    {
      true, true, true, true, false },

    // persistent-clean
    {
      true, true, false, false, false },

    // persistent-dirty
    {
      true, true, true, false, false },

    // hollow
    {
      true, false, false, false, false },

    // transient-clean
    {
      false, true, false, false, false },

    // transient-dirty
    {
      false, true, true, false, false },

    // persistent-new-deleted
    {
      true, true, true, true, true },

    // persistent-deleted
    {
      true, true, true, false, true },

    // persistent-nontransactional
    {
      true, false, false, false, false }
  };

  /**
   *This utility method returns a <code>String</code> that indicates the current state of an instance.
   *@param o The object.
   *@return The current state of the instance, by using the <code>JDOHelper</code> state
   *interrogation methods.
   */
  public static String getStateOfInstance(Object o)
  {
    boolean existingEntries = false;
    StringBuffer buff = new StringBuffer("{");
    if( JDOHelper.isPersistent(o) ){
      buff.append("persistent");
      existingEntries = true;
    }
    if( JDOHelper.isTransactional(o) ){
      if( existingEntries ) buff.append(", ");
      buff.append("transactional");
      existingEntries = true;
    }
    if( JDOHelper.isDirty(o) ){
      if( existingEntries ) buff.append(", ");
      buff.append("dirty");
      existingEntries = true;
    }
    if( JDOHelper.isNew(o) ){
      if( existingEntries ) buff.append(", ");
      buff.append("new");
      existingEntries = true;
    }
    if( JDOHelper.isDeleted(o) ){
      if( existingEntries ) buff.append(", ");
      buff.append("deleted");
    }
    buff.append("}");
    return buff.toString();
  }
 
  public static int currentState(Object o) {
    boolean[] status = new boolean[5];
    status[IS_PERSISTENT] = JDOHelper.isPersistent(o);
    status[IS_TRANSACTIONAL] = JDOHelper.isTransactional(o);
    status[IS_DIRTY] = JDOHelper.isDirty(o);
    status[IS_NEW] = JDOHelper.isNew(o);
    status[IS_DELETED] = JDOHelper.isDeleted(o);
    int i, j;
    outerloop : for (i = 0; i < NUM_STATES; ++i) {
      for (j = 0; j < NUM_STATUSES; ++j) {
        if (status[j] != state_statuses[i][j])
          continue outerloop;
      }
      return i;
    }
    return NUM_STATES;
  }

// These values MUST correspond to index in sorted array below.
  private static final int OPTION_APPLICATIONIDENTITY       = 0;
  private static final int OPTION_ARRAY                     = 1;
  private static final int OPTION_ARRAYLIST                 = 2;
  private static final int OPTION_CHANGEAPPLICATIONIDENTITY = 3;
  private static final int OPTION_DATASTOREIDENTITY         = 4;
  private static final int OPTION_HASHMAP                   = 5;
  private static final int OPTION_HASHTABLE                 = 6;
  private static final int OPTION_LINKEDLIST                = 7;
  private static final int OPTION_LIST                      = 8;
  private static final int OPTION_MAP                       = 9;
  private static final int OPTION_NONDURABLEIDENTITY        = 10;
  private static final int OPTION_NONTRANSACTIONALREAD      = 11;
  private static final int OPTION_NONTRANSACTIONALWRITE     = 12;
  private static final int OPTION_NULLCOLLECTION            = 13;
  private static final int OPTION_OPTIMISTIC                = 14;
  private static final int OPTION_RETAINVALUES              = 15;
  private static final int OPTION_TRANSIENTTRANSACTIONAL    = 16;
  private static final int OPTION_TREEMAP                   = 17;
  private static final int OPTION_TREESET                   = 18;
  private static final int OPTION_VECTOR                    = 19;

  private static boolean[] options = new boolean[OPTION_VECTOR + 1];
 
 
  static {
    for (int i=0; i< OPTION_VECTOR+1; i++)
      options[i] = true;
   
    options[OPTION_CHANGEAPPLICATIONIDENTITY] = false;
    options[OPTION_NONDURABLEIDENTITY] = false;
  }
 
 
  /**
   * Reports whether Optimistic is supported.
   */
  public static boolean isOptimisticSupported() {
    return options[OPTION_OPTIMISTIC];
  }


  static PersistenceManager   pm10 = null;
  static PersistenceManager   pm20 = null;

 
 
  BasicA ba1 = null;
  BasicA ba2 = null;
  BasicA ba3 = null;
  BasicA ba4 = null;
  BasicA ba5 = null;
  private PersistenceManager pm;
  private Transaction tx;

  BasicA b1 = null;
  private int totalThreadCount = 10;
  private int completedThreadCount = 0;
  private int succeeds = 0;
  private int catchNumber = 0;

  public PersistenceManagerTck(String s) {
    super(s);
  }

  protected String getLoggerName() {
    return LOG_NAME + ".rt.tck.PersistenceManagerTck";
  }

 
  protected PersistenceManager getPM() {
    if (pm == null) {
      pm = getPMF().getPersistenceManager();
    }
    return pm;
  }

  protected void closePM() {
    if (pm != null) {
      pm.close();
      pm = null;
    }
  }

/*
  private void createObjects() {
    try {

      getPM().currentTransaction().begin();
      ba1 = new BasicA();
      ba2 = new BasicA();
      ba3 = new BasicA();
      ba4 = new BasicA();
      ba5 = new BasicA();

      getPM().makePersistent(ba1);
      getPM().makePersistent(ba2);
      getPM().makePersistent(ba3);
      getPM().makePersistent(ba4);
      getPM().makePersistent(ba5);

      getPM().currentTransaction().commit();

    } catch (Exception ex) {
      logger.log(BasicLevel.ERROR, "Unexception caught in createObjects", ex);
      closePM();
      fail(ex.getMessage());
    }
  }
*/
 
  public void  testConcurrentPersistenceManagersSameClasses() {

    logger.log(BasicLevel.INFO, "testConcurrentPersistenceManagersSameClasses");
    Properties pmfProperties = loadPMF2Properties();
    PersistenceManagerFactory pmf2 = JDOHelper.getPersistenceManagerFactory(pmfProperties);
    PersistenceManager pm2 = pmf2.getPersistenceManager();
    logger.log(BasicLevel.DEBUG, "begin getTransactions");
    Transaction tx2 = pm2.currentTransaction();
    tx = getPM().currentTransaction();
    logger.log(BasicLevel.DEBUG, "begin initData");
    tx.begin();
    tx2.begin();

    BasicA ba11 = new BasicA();
    ba11.writeF1("ba11");
    BasicA ba12 = new BasicA();
    ba11.writeF1("ba12");

    getPM().makePersistent(ba11);
    getPM().makePersistent(ba12);

    BasicA ba21 = new BasicA();
    ba11.writeF1("ba21");
    BasicA ba22 = new BasicA();
    ba11.writeF1("ba22");

    pm2.makePersistent(ba21);
    pm2.makePersistent(ba22);

    tx.commit();
    tx2.commit();

    logger.log(BasicLevel.DEBUG, "begin test");
    tx.begin();
    tx2.begin();

    BasicA ba11a = findBasicA(pm, "ba11");
    Assert.assertEquals(ba11a, ba11);

    BasicA ba21a = findBasicA(pm2, "ba21");
    Assert.assertEquals(ba21a, ba21);

    tx.commit();
    tx2.commit();

    closePM();
    pm2.close();

    logger.log(BasicLevel.DEBUG, "passed in testConcurrentPersistenceManagersSameClasses");

  }

  Properties loadPMF2Properties() {
/*
    String PMF2 = System.getProperty("PMF2Properties", "c:\\jdotck\\jdori2.properties");
    logger.log(BasicLevel.DEBUG, "Got PMF2Properties file name:" + PMF2);
    Properties ret = loadProperties(PMF2);
    logger.log(BasicLevel.DEBUG, "Got PMF2Properties: " + ret);
*/
    return getPMFPropertiesFromFile();
  }

  BasicA findBasicA(PersistenceManager pm, String param) {
    Query q = pm.newQuery(BasicA.class);
    q.declareParameters("String param");
    q.setFilter("(param == f1)");
    Collection results = (Collection) q.execute(param);
    Iterator it = results.iterator();
    BasicA ret = (BasicA) it.next();
    return ret;
  }

  /**
   * This method load Properties from a given file.
   */
  protected Properties loadProperties(String fileName) {
    if (fileName == null) {
      fileName = System.getProperty("user.dir") + "/jdori2.properties";
    }
    Properties props = new Properties();
    InputStream propStream = null;
    try {
      propStream = new FileInputStream(fileName);
    } catch (java.io.IOException ex) {
      logger.log(BasicLevel.ERROR, "Could not open properties file \"" + fileName + "\"");
      logger.log(
        BasicLevel.ERROR,
        "Please specify PMF properties file name"
          + " -PMFProperties argument (defaults to {user.dir}/jdori2.properties)");
      System.exit(1);
    }
    try {
      props.load(propStream);
    } catch (java.io.IOException ex) {
      logger.log(BasicLevel.ERROR, "Error loading properties file \"" + fileName + "\"", ex);
      System.exit(1);
    }
    return props;
  }

  public void testDeletePersistentFailsIfInstanceManagedByAnotherPersistenceManager() {
    logger.log(BasicLevel.INFO, "testDeletePersistentFailsIfInstanceManagedByAnotherPersistenceManager");
    pmf = getPMF();
    PersistenceManager pm1 = pmf.getPersistenceManager();
    PersistenceManager pm2 = pmf.getPersistenceManager();
   
   
    Assert.assertTrue("same persistence manager", !pm1.equals(pm2));

    try {

      pm1.currentTransaction().begin();
      ba1 = new BasicA();
      ba2 = new BasicA();
      ba3 = new BasicA();
      ba4 = new BasicA();
      ba5 = new BasicA();

      pm1.makePersistent(ba1);
      pm1.makePersistent(ba2);
      pm1.makePersistent(ba3);
      pm1.makePersistent(ba4);
      pm1.makePersistent(ba5);
      pm = JDOHelper.getPersistenceManager(ba1);
      logger.log(BasicLevel.DEBUG, "before commit pm="+pm);     
      pm1.currentTransaction().commit();
      pm = JDOHelper.getPersistenceManager(ba1);
      logger.log(BasicLevel.DEBUG, "after commit pm="+pm);     
     

    } catch (Exception ex) {
      logger.log(
        BasicLevel.ERROR,
        "Unexception caught in testDeletePersistentFailsIfInstanceManagedByAnotherPersistenceManager",
        ex);
      pm1.close();
      pm2.close();
      fail(ex.getMessage());
    }

    /* test deletePersistent (Object pc) */
    try {

      pm2.currentTransaction().begin();
      pm = JDOHelper.getPersistenceManager(ba1);
      logger.log(BasicLevel.DEBUG, "pm1="+pm1 + "  pm="+pm);
      Assert.assertTrue("not same persistence manager 1", pm1.equals(pm));     
      pm2.deletePersistent(ba1);     
      logger.log(BasicLevel.DEBUG, "pm2="+pm2 + "  pm="+pm);
           
      throw new Exception("FAILED in deletePersistentPM2() - should not go that further");
    } catch (Exception ex) {
      if (ex instanceof JDOUserException) {
        ; // expected result
      } else {
        logger.log(BasicLevel.ERROR, "Unexception caught in deletePersistentPM2", ex);
       
      }
      pm2.currentTransaction().rollback();
    }
   
    /* test deletePersistentAll (Collection pcs) */
    try {
      pm2.currentTransaction().begin();

      Collection col1 = new java.util.HashSet();
      col1.add(ba2);
      col1.add(ba3);

      pm2.deletePersistentAll(col1);

      throw new Exception("FAILED in deletePersistentAll1() - should not go that further");
    } catch (Exception ex) {
      if (ex instanceof JDOUserException) {
        ; // expected result
      } else {
        logger.log(BasicLevel.ERROR, "Unexception caught in deletePersistentAll1", ex);
      }
      pm2.currentTransaction().rollback();
    }
   
    /* test deletePersistentAll (Object[] o) */
    try {

      pm2.currentTransaction().begin();

      Collection col1 = new java.util.HashSet();
      col1.add(ba4);
      col1.add(ba5);

      Object[] obj1 = col1.toArray();

      pm2.deletePersistentAll(obj1);

      throw new Exception("FAILED in deletePersistentAll2() - should not go that further");
    } catch (Exception ex) {
      if (ex instanceof JDOUserException) {
        ; // expected result
      } else {
        logger.log(BasicLevel.ERROR, "Unexception caught in deletePersistentAll2", ex);
      }
      pm2.currentTransaction().rollback();
    }
   

    logger.log(BasicLevel.DEBUG, "passed in testDeletePersistentFailsIfInstanceManagedByAnotherPersistenceManager");

    pm1.close();
    pm2.close();

  }


  public void testOneInstanceOfObjectPerPersistenceManager() {
    logger.log(BasicLevel.INFO, "testOneInstanceOfObjectPerPersistenceManager");
    tx = getPM().currentTransaction();
    //tx.setRetainValues(false);
    tx.setRestoreValues(false);

    tx.begin();
    BasicA ba11 = new BasicA();
    ba11.writeF1("ba11");
    getPM().makePersistent(ba11);
    tx.commit();

    tx.begin();
    Object p1Id = getPM().getObjectId(ba11);
    BasicA ba11a = (BasicA) getPM().getObjectById(p1Id, true);
    BasicA ba11c = findBasicA(getPM(), "ba11");
    tx.commit();
    closePM();

    Assert.assertEquals("Assertion A5.4-2 failed; getObjectById results differ", ba11a, ba11);
    Assert.assertEquals("Assertion A5.4-2 failed; query results differ", ba11c, ba11);
    tx = getPM().currentTransaction();
    tx.begin();
    getPM().deletePersistent(ba11);
    tx.commit();
    closePM();

    logger.log(BasicLevel.DEBUG, "passed in testOneInstanceOfObjectPerPersistenceManager");
  }

  public void testRefreshAllWithNoParameters() {
    logger.log(BasicLevel.INFO, "testRefreshAllWithNoParameters");
    tx = getPM().currentTransaction();
    tx.begin();
    BasicA ba11 = new BasicA();
    ba11.writeF1("ba11");
    ba11.writeF2(200);
    getPM().makePersistent(ba11);
    tx.commit();

    tx.begin();
    ba11.writeF1("xx");
    //ba11.writeF2(800);

    /*
     * Collection col1 = new java.util.HashSet(); col1.add(ba11); try { getPM().refresh(ba11); } catch (Exception
     * ex) { logger.log(BasicLevel.DEBUG, "passed in refresh(ba11)" + ex.getMessage()); }
     *
     * try { getPM().refresh(col1); } catch (Exception ex) { logger.log(BasicLevel.DEBUG, "passed in refresh(col1)" +
     * ex.getMessage()); }
     */
    getPM().refreshAll();

    Assert.assertEquals("Assertion A12.5.1-6 failed; values not refreshed", ba11.readF1(), "ba11");
    Assert.assertEquals("Assertion A12.5.1-6 failed; values not refreshed", ba11.readF2(), 200);
    tx.commit();
    closePM();
    logger.log(BasicLevel.DEBUG, "passed in testRefreshAllWithNoParameters");
  }

  public void testThreadSafe() {
    logger.log(BasicLevel.INFO, "testThreadSafe");
    try {

      /**
       * The implementation must synchronize instances of PersistenceCapable during state transitions that
       * replace the StateManager. This is to avoid race conditions where the application attempts to make the
       * same instance persistent in multiple PersistenceManagers.
       */

      b1 = new BasicA();
      for (int i = 0; i < totalThreadCount; i++) {
        Thread t = new Thread(new PMThread(pmf, b1, this));
        t.setName("ThreadSafeID-" + i);
        t.start();
      }

      while (totalThreadCount != completedThreadCount) {
        try {
          Thread.sleep(100);
        } catch (InterruptedException ex) {
          logger.log(BasicLevel.INFO, "interrupted");
        }
      }

      //logger.log(BasicLevel.DEBUG, "succeeds=" + succeeds + " catchNumber=" + catchNumber);

      /**
       * Only the first thread may
       */
      Assert.assertTrue("Failed: succeeds = "+succeeds+ " catchNumber = "+catchNumber, ((succeeds == 1) && (catchNumber == totalThreadCount - 1)));

    } catch (Exception ex) {
      logger.log(BasicLevel.ERROR, "Unexception caught in testThreadSafe", ex);
      fail(ex.getMessage());
    }

  }

  protected synchronized void complete() {
    completedThreadCount++;
  }

  protected synchronized void winning(BasicA pc) {
    logger.log(BasicLevel.DEBUG, "*** ThreadID : " + Thread.currentThread().getName() + " succeeds");
    succeeds++;
  }

  class PMThread implements Runnable {
    private final PersistenceManager pm;
    private final Object pc;
    private final PersistenceManagerTck owner;

    PMThread(PersistenceManagerFactory pmf, BasicA pc, PersistenceManagerTck owner) {

      this.pm = pmf.getPersistenceManager(); // should return different pm
      this.pc = pc;
      this.owner = owner;
    }

    public void run() {
      Transaction tx = null;
      try {
        logger.log(BasicLevel.DEBUG, " Running thread: " + Thread.currentThread().getName());
        // the application attempts to make the same instance persistent in multiple PersistenceManagers.
        tx = pm.currentTransaction();
        tx.begin();       
        logger.log(BasicLevel.DEBUG, "before makePersistent pm="+pm);     
        pm.makePersistent(pc);       
        logger.log(BasicLevel.DEBUG, "after makePersistent pm="+JDOHelper.getPersistenceManager(pc));
        tx.commit();
        winning((BasicA) pc);
        complete();

        while (totalThreadCount != completedThreadCount) {
          try {
            Thread.sleep(100);
          } catch (InterruptedException ex) {
            logger.log(BasicLevel.INFO, "interrupted");
          }
        }
      } catch (Exception ex) {
        catchNumber++;
        if (ex instanceof JDOUserException) {
          logger.log(
            BasicLevel.DEBUG,
            "JDOUserException caught in PMThread.run()" + Thread.currentThread().getName(),
            ex);
          ; // expected result
        } else {
          logger.log(
            BasicLevel.ERROR,
            "Unexception caught in PMThread.run()" + Thread.currentThread().getName(),
            ex);
        }
        complete();
      } finally {
        try {
          if (tx.isActive()) {
            tx.rollback();
          }
          pm.close();
        } catch (Exception fex) {
          logger.log(BasicLevel.ERROR, "Unexception caught in PMThread()", fex);
        }
      }
    } // run

  } // class PMThread

  public Object createBasicAInstance() {
    try {
      BasicA p1 = new BasicA();
      pm = getPM();

      tx = pm.currentTransaction();
      tx.begin();
      pm.makePersistent(p1);
      Object oid = pm.getObjectId(p1);
      tx.commit();
      return oid;
    } catch (Exception ex) {
      logger.log(BasicLevel.ERROR, "Unexception caught in createPCPointInstance", ex);
      return null;
    }
  }
 
  public void testGetObjectById() {
    logger.log(BasicLevel.INFO, "testGetObjectById");
    try {

      Object oid = createBasicAInstance();

      // nontransactional access
      logger.log(BasicLevel.DEBUG, "nontransactional");
      pm = null; // make sure to get a different pm so obj is not in cache
      tx = getPM().currentTransaction();
      tx.setNontransactionalRead(true);
      Object obj = pm.getObjectById(oid, true);
      int state = currentState(obj);
      if (state != PERSISTENT_NONTRANSACTIONAL & state != HOLLOW) {
        //incrementErrorCount();
        logger.log(
          BasicLevel.ERROR,
          "Expected persistent-nontransactional or hollow; got " + getStateOfInstance(obj));
      }

      // pessimistic transactional access
      logger.log(BasicLevel.DEBUG, "pessimistic");
      pm = null; // make sure to get a different pm so obj is not in cache
      tx = getPM().currentTransaction();
      tx.setOptimistic(false);
      tx.begin();
      obj = pm.getObjectById(oid, true);
      state = currentState(obj);
      tx.commit();
      if (state != PERSISTENT_CLEAN) {
        //incrementErrorCount();
        logger.log(BasicLevel.ERROR, "Expected persistent-clean; got " + getStateOfInstance(obj));
      }

      // optimistic transactional access
      if (isOptimisticSupported()) {
        logger.log(BasicLevel.DEBUG, "optimistic");
        pm = null; // make sure to get a different pm so obj is not in cache
        tx = getPM().currentTransaction();
        tx.setOptimistic(true);
        tx.begin();
        obj = pm.getObjectById(oid, true);
        state = currentState(obj);
        tx.commit();
        if (state != PERSISTENT_NONTRANSACTIONAL & state != HOLLOW) {
          //incrementErrorCount();
          logger.log(
            BasicLevel.ERROR,
            "Expected persistent-nontransactional; got " + state + getStateOfInstance(obj));
        }
      } else {
        logger.log(BasicLevel.INFO, "optimistic test skipped");
      }
    } catch (Exception ex) {
      logger.log(BasicLevel.ERROR, "Unexception caught in testGetObjectById", ex);
      fail(ex.getMessage());
    }
  }
 
  public void testRefreshSideEffects() {
    logger.log(BasicLevel.INFO, "testRefreshSideEffects");

    pm10 = getPMF().getPersistenceManager();
    pm20 = getPMF().getPersistenceManager();
   
    try {

      RefreshThreadT1 thread1 = new RefreshThreadT1(logger);
      Thread  T1 = new Thread(thread1);
      RefreshThreadT2 thread2 = new RefreshThreadT2(logger);
      Thread  T2 = new Thread(thread2);

      T1.start();
      T2.start();

      T1.join();
      T2.join();

      logger.log(BasicLevel.DEBUG, "thread1.state="+thread1.state);
      logger.log(BasicLevel.DEBUG, "thread2.state="+thread2.state);
      if (thread1.state != 1 || thread2.state != 1)
        logger.log(BasicLevel.ERROR, "RefreshSideEffects: thread1.state="+thread1.state+" thread2.state="+thread2.state);
        //incrementErrorCount();

    } catch (Exception ex) {
      logger.log(BasicLevel.ERROR, "Unexception caught in testRefreshSideEffects", ex);
      fail(ex.getMessage());
    }
   
  }
 
}

class RefreshThreadT1 implements Runnable {
 
  volatile int state=0;
  static final int DELAY=100;
  static boolean commitDone = false;
  static boolean doneFlag = false;
  Transaction tx1 = null;
  Logger logger = null;
  static BasicA n1 = new BasicA();

  RefreshThreadT1(Logger logger) {
    tx1 = PersistenceManagerTck.pm10.currentTransaction();
    tx1.setOptimistic(true);
    this.logger = logger;
   
  }

  public static void initVariables() {
    commitDone = false;
    doneFlag = false;
  }

  synchronized public void run() {
    try {
      state=1;
      tx1.begin();
      n1.writeF2(500);
      PersistenceManagerTck.pm10.makePersistent(n1);
      PersistenceManagerTck.pm10.refresh(n1);

      while (! RefreshThreadT2.doneFlag) {
        Thread.sleep(DELAY);
      }

      tx1.commit();
      commitDone = true;


    } catch (Exception ex) {
      //out.println (" Exception in T1 run ");
      //ex.printStackTrace(out);
      state = 13;
      logger.log(BasicLevel.ERROR, "Unexception caught in RefreshThreadT1", ex);
    }
  }

}

class RefreshThreadT2 implements Runnable {


  volatile int state=0;
  static final int DELAY=100;
  static boolean commitDone = false;
  static boolean doneFlag = false;
  Transaction tx2 = null;
  Logger logger = null;
  static BasicA p1 = new BasicA();

  RefreshThreadT2(Logger logger) {
    tx2 = PersistenceManagerTck.pm20.currentTransaction();
    tx2.setOptimistic(true);
    this.logger = logger;
  }

  public static void initVariables() {
    commitDone = false;
    doneFlag = false;
  }

  /* test refresh() */
  synchronized public void run() {
    try {
      state=1;
      tx2.begin();
      p1.writeF2(201);
      PersistenceManagerTck.pm20.makePersistent(p1);
      PersistenceManagerTck.pm20.refresh(p1);
      doneFlag = true;

      while (! RefreshThreadT1.commitDone) {
        Thread.sleep(DELAY);

      }
      tx2.commit();
      commitDone = true;


    } catch (Exception ex) {
      state=10;
      logger.log(BasicLevel.ERROR, "Unexception caught in RefreshThreadT2", ex);
    }
  }

}

TOP

Related Classes of org.objectweb.speedo.runtime.tck.PersistenceManagerTck$PMThread

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.