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.



Example for java.util.concurrent.locks.ReentrantReadWriteLock usage


Let's try the latest sample with another beauty of the java.util.concurrent package :ReentrantReadWriteLock



import java.util.concurrent.locks.*;

public class ReentrantReadWriteLockExample {
    int i = 0;

    public static void main (String[] args) {
        final ReentrantReadWriteLockExample example = new ReentrantReadWriteLockExample();
        final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

        final Runnable r = new Runnable () {
            public void run () {
                while (true) {
                    try {
                        lock.writeLock().lock();
                        //Here is the critical section jobs are being done securely..
                        example.printSomething ();
                        Thread.sleep (1000);
                        lock.writeLock().unlock();
                    } catch (Exception ex) {
                        System.out.println (" -- Interrupted...");
                        ex.printStackTrace ();
                    }
                }
            }
        };

        new Thread (r).start ();
        new Thread (r).start ();
        new Thread (r).start ();
    }

    public void printSomething (){
        i++;
        System.out.println (" -- current value of the i :"+ i);
    }
}

Thursday, October 7, 2010

Example for java.util.concurrent.Semaphore usage

Let's try to increment a simple integer variable without any synchronization.
See what happens if we don't care about critical sections :)


Yes even we are not able to increment an integer without using any synchronization primitives.So we see the values of "i" 10-11-10 which are highlighted in the messages pane of my ide.

And...Here is the succesfull result in which we are using a Semaphore from java 1.5 (Tiger).

import java.util.concurrent.locks.*;
import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    int i = 0;

    public static void main (String[] args) {
        final SemaphoreExample example = new SemaphoreExample();
        final Semaphore semaphore = new Semaphore (1);

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

        new Thread (r).start ();
        new Thread (r).start ();
        new Thread (r).start ();
    }

    public void printSomething (){
        i++;
        System.out.println (" -- current value of the i :"+ i);
    }
}