Hi,

¿ Is it possible to use Test & Set business logic using synchronized blocks in 
persistent instances ?

Each objectContext has its own instances, then there may be many copies of the 
same object identity (id) in memory, that keep in sync with each other if you 
commit, ¿ Is it possible to use normal java synchronized block  ?

I've build the next test using two threads, and when it runs, the field is 
modified twice, under normal java concepts, only one thread should succeed.

Note: Factory, is a repository with static methods to manage persistence 
(finally calls ObjectContext and DataContext).


package cl.company.test;

import cl.company.domain.Usuario;
import cl.company.domain.Factory;

/**
 * Concurrency over same instance, test & set. * @author hans
 *
 */
public class TestConcurrenciaCayenne implements Runnable {

        private static final int USER_ID = 1000;
        String name;

        public TestConcurrenciaCayenne(String name) {
                this.name = name;
        }

        public static void main(String[] args) {

                Factory.createAndBindDataContext();

                Usuario c = Factory.getUsuario(USER_ID);
                c.setEsInactivo(true);
                Factory.commit();

                TestConcurrenciaCayenne t1 = new TestConcurrenciaCayenne("t1");
                TestConcurrenciaCayenne t2 = new TestConcurrenciaCayenne("t2");
                new Thread(t1).start();
                new Thread(t2).start();
        }

        @Override
        public void run() {

                Factory.createAndBindDataContext();

                Usuario c = Factory.getUsuario(USER_ID);
                System.out.println("Before synchronized block " + this.name);
                synchronized (c) {

                        System.out.println("Inside the block " + this.name);
                        if (c.getEsInactivo()) {
                                try {
                                        Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                        e.printStackTrace();
                                }
                                c.setEsInactivo(false);
                                System.out.println("Modifyin " + this.name);
                        }

                        Factory.commit();

                }

        }

}



Thanks
Hans

Reply via email to