Friday, November 12, 2010

IODH

Zero Syncronization issues ! Simple ! Clean !

public class Something {
private Something() {
}

private static class LazyHolder {
private static final Something INSTANCE = new Something();
}

public static final Something getInstance() {
return LazyHolder.INSTANCE;
}
}

OR

static Singleton instance;

public static synchronized Singleton getInstance() {
if (instance == null)
instance == new Singleton();
return instance;
}

Why it is called LAZY ? : IODH utilizes lazy class initialization. The JVM won't execute a class's static initializer until you actually touch something in the class. This applies to static nested classes, too...

Read more on : wikipedia , Double-checked_locking

Wednesday, November 3, 2010

Transaction isolation levels and 3 phenomena..


dirty read
A transaction reads data written by a concurrent uncommitted transaction.
nonrepeatable read
A transaction re-reads data it has previously read and finds that data has been modified by another transaction (that committed since the initial read).
phantom read
A transaction re-executes a query returning a set of rows that satisfy a search condition and finds that the set of rows satisfying the condition has changed due to another recently-committed transaction.
Isolation Level Dirty Read Nonrepeatable Read Phantom Read
Read uncommitted Possible Possible Possible
Read committed Not possible Possible Possible
Repeatable read Not possible Not possible Possible
Serializable Not possible Not possible Not possible

see also : http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html Similar things to Java's ReentrantReadWriteLock

Thursday, October 28, 2010

Basic Drools example!

what is wrong with this ??

rule "Apply 10% discount if total purcahses is over 100"           
    no-loop true   
    dialect "java"
    when
        $c : Customer()
        $i : Double(doubleValue  > 100) from accumulate ( Purchase( customer == $c, $price : product.price ),
                                                                    sum( $price ) )
    then
          $c.setDiscount( 10 );
        insertLogical( new Discount($c, 10) );   
        System.out.println( "Customer " + $c.getName() + " now has a shopping total of " + $i );
end

Hi All,

We see a part of .drl file above :) I have found it in the Drools 5.1 examples.I tried to understand it's world. I can not define exactly but i think there is something dirty around here.

I write java. I want to write java. I know java (I guess:))...

But what is the no-loop & accumulate & sum & insertLogical & assigments in text & calling java methods from a text file ?

Why i have have learn some other literals ? If I am expected & free to write Java in there (meaning lovely .drl file) why & what the other things are ?

Come on guys. I am someone who really curious for new technologies. I am not resisting to learn those.


Only those make me scared . Calling my methods  from a text file ??? i was expecting to see only execution paths (in some other clean waylike when->what). Maybe I could implement some interfaces i could return some preDefined RETURN_TYPEs also. Even I could write simple Java Statements in an XML file. Those are all accepted by me.

But,,, Calling java methods from text context, doing assignments in there .Learning its nature .....I felt myself like developing PLSQL . I don't want implement a business logic inside a text file. I don't know why ...Just my comments.

PS: I could validate a xml file or Java file in my IDE (which is not eclipse). I don't want to be mad bec.of a typo or some extra comma while dealing with a weird text file in the future.


Sorry...

I will be searching for another fwk ....

****

A few days later....

A small update :

1) Download JSR94 jar :Java Rule Engine Specification
http://jcp.org/aboutJava/communityprocess/final/jsr094/index.html
2) Download JRuleEngine from :
http://sourceforge.net/projects/jruleengine/files/
3) Create a project with these 2 jars. Compile and run ..

See sample rule.xml :

I liked it very much...Sweet huh ?

Nevertheless I have a question mark for JRuleEngine too. As a commentator :D

In its web page there is a link: To do:

It says :
- Rules graphical editor: a JSP web application to define rules that will be saved on XML file.



****

JSP's and web applications is a good but i think it is not the right choice.
Application Management and Monitoring must be done via MBeans. JConsole a is good tool.

InputStream inStream = new FileInputStream( "/home/sunels/JRuleEngine1.3/examples/example1.xml" );
RuleExecutionSet res1 = ruleAdministrator.getLocalRuleExecutionSetProvider(null).createRuleExecutionSet( inStream, null );


Maybe rules can be served as a mbean while creating the RuleExecutionSet...

Friday, October 22, 2010

Are java constructors thread safe ?

For instance fields YES ...
For static fields NO...
Let's Proove it ...

public class TestObject {
    private static int dangerInt =0 ;

    public TestObject () {
            dangerInt++;
            System.out.println (" Current Value of i :" + dangerInt + "     # -- " + Thread.currentThread ().getName ());
    }
}

public class ConstructorTest {

    public static void main (String[] args) {
        final ConstructorTest test = new ConstructorTest();

        final Runnable r = new Runnable () {
            public void run () {
                while (true) {
                    try {
                        test.printSomething ();
                        Thread.sleep (500);
                    } catch (Exception ex) {
                        System.out.println (" -- Interrupted...");
                        ex.printStackTrace ();
                    }
                }
            }
        };

        for (int i = 0; i < 10; i++) {
            new Thread (r).start ();
        }

    }

    public void printSomething (){
        new TestObject ();
    }
}
Output :  Current Value of i :2     # -- Thread-1
 Current Value of i :2     # -- Thread-0
 Current Value of i :3     # -- Thread-2
 Current Value of i :4     # -- Thread-3
 Current Value of i :5     # -- Thread-4
 Current Value of i :6     # -- Thread-5
 Current Value of i :7     # -- Thread-6
 Current Value of i :8     # -- Thread-7
 Current Value of i :9     # -- Thread-8
 Current Value of i :10     # -- Thread-9
 Current Value of i :11     # -- Thread-1
 Current Value of i :12     # -- Thread-0
 Current Value of i :13     # -- Thread-2
 Current Value of i :14     # -- Thread-3
 Current Value of i :15     # -- Thread-4
 Current Value of i :16     # -- Thread-5
 Current Value of i :17     # -- Thread-6
 Current Value of i :18     # -- Thread-7
 Current Value of i :19     # -- Thread-8
 Current Value of i :20     # -- Thread-9
 Current Value of i :21     # -- Thread-1
 Current Value of i :22     # -- Thread-0
 Current Value of i :23     # -- Thread-2
 Current Value of i :24     # -- Thread-3
 Current Value of i :25     # -- Thread-4
 Current Value of i :26     # -- Thread-5
 Current Value of i :27     # -- Thread-6
 Current Value of i :28     # -- Thread-7
 Current Value of i :29     # -- Thread-8
 Current Value of i :30     # -- Thread-9
 Current Value of i :31     # -- Thread-1
 Current Value of i :32     # -- Thread-0
 Current Value of i :33     # -- Thread-2
 Current Value of i :34     # -- Thread-3
 Current Value of i :35     # -- Thread-4
 Current Value of i :36     # -- Thread-5
 Current Value of i :37     # -- Thread-6
 Current Value of i :38     # -- Thread-7
 Current Value of i :39     # -- Thread-8
 Current Value of i :40     # -- Thread-9
 Current Value of i :41     # -- Thread-1
 Current Value of i :42     # -- Thread-0
 Current Value of i :43     # -- Thread-2
 Current Value of i :44     # -- Thread-3
 Current Value of i :45     # -- Thread-4
 Current Value of i :46     # -- Thread-5
 Current Value of i :47     # -- Thread-6
 Current Value of i :48     # -- Thread-7
 Current Value of i :49     # -- Thread-8
 Current Value of i :50     # -- Thread-9
 Current Value of i :51     # -- Thread-1
 Current Value of i :53     # -- Thread-3
 Current Value of i :55     # -- Thread-5
 Current Value of i :57     # -- Thread-7
 Current Value of i :54     # -- Thread-6
 Current Value of i :58     # -- Thread-8
 Current Value of i :56     # -- Thread-4
 Current Value of i :52     # -- Thread-2
 Current Value of i :51     # -- Thread-0

Monday, October 11, 2010

Solving Leader Election Problem in a Clustered enviroment with JGroups

First of all this blog entry is written for jgroups 2.5.1 and  now jgroups.3-0-1-final is available and example is rewritten by me.

It is remommended to use new api. Because DistributedLock class is deprecated. Have a look at the new blog entry . 

Let me jump in the source code again without any amateur explaination about Leader Election Problem.

Scenario : There will be three competitor in our cluster. First one will be the master (~leader) because there is no other one currently.

Second and Third One(s) won't have a chance to get "Distributed Lock". After a while our master will be killed by us with a big pleasure :)

Then we will see new MASTER(~leader of our cluster).You can see the message on  snapshots below.

import org.jgroups.*;
import org.jgroups.blocks.DistributedLockManager;
import org.jgroups.blocks.VotingAdapter;
import org.jgroups.blocks.NotificationBus;
import org.jgroups.blocks.LockNotGrantedException;

import java.io.Serializable;

public class TheOne extends ReceiverAdapter {

    private JChannel channel;
    private volatile boolean becomeMaster;
    private DistributedLockManager lockManager;
    private VotingAdapter adapter;

    public static void main(String[] args) throws Exception {
        System.setProperty("jgroups.bind_addr", "10.34.34.137");//use your ip address
        TheOne master = new TheOne();
        master.start();
    }


    public void start() throws ChannelException {
        channel = new JChannel("udp.xml");
        adapter = new VotingAdapter(channel);
        adapter.addMembershipListener(this);
        lockManager = new DistributedLockManager(adapter, "DistributedLockManager");
        channel.connect("ClassPresidentCluster");
    }


    public void viewAccepted(final View new_view) {
        new Thread() {
            public void run() {
                System.out.println("new view " + new_view);
                getLock();
            }
        }.start();
    }


    private void getLock() {
        if (becomeMaster) {
            System.out.println("-- STILL I am the ONE !!");
            return;
        }
        try {
            System.out.println("looking for lock");
            System.out.println(lockManager);
            System.out.println(adapter);
            lockManager.lock("writer", channel.getAddress(), 0);
            becomeMaster = true;
            System.out.println(" -- I AM THE ONE !!!");
        } catch (ChannelException e) {
            e.printStackTrace();
        } catch (LockNotGrantedException e) {
            System.out.println("no lock for me :(");
        }
    }
}


1)First competitor comes to area a becomes a master very easily.

2)Second competitor comes to area but lock is owned by the first one.

3)Third competitor comes to area but lock is owned by the first one still.


4)After killing the master second one becomes a MASTER.