Saturday, March 20, 2010

Interfaces and Implementations

Suppose that you are building an
ABSTRACT FACTORY for the creation of shapes. This factory will be an interface and will be implemented by a concrete class. What should you name them? IShapeFactory and ShapeFactory? I prefer to leave interfaces unadorned. The preceding I, so common in today’s legacy wads, is a distraction at best and too much information at worst. I don’t want my users knowing that I’m handing them an interface. I just want them to know that it’s a ShapeFactory. So if I must encode either the interface or the implementation, I choose the implementation. Calling it shapeFactoryImp, or even the hideous CShapeFactory, is preferable to encoding the interface.


In general programmers are pretty smart people. Smart people sometimes like to show off their smarts by demonstrating their mental juggling abilities. After all, if you can reliably remember that r is the lower-cased version of the url with the host and scheme removed, then you must clearly be very smart.
One difference between a smart programmer and a professional programmer is that the professional understands that clarity is king. Professionals use their powers for good and write code that others can understand.

   --Clean Code by Robert C. Martin

Wednesday, March 17, 2010

Atomically incremented counters

    private final static int startIndex = 1;
    private final static int pageSize = 5000;

    private AtomicInteger pageNo = new AtomicInteger(startIndex);

    private int getNextPage (){
        return pageNo.getAndIncrement();
    }

insteadOf**


    int pageNo = 0;

    private synchronized int getNextPage (){
        pageNo++;
        return pageNo;
    }



#####################################
#                                          More on it
#####################################



import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerUsage {
    private final static int startIndex = 1;
    private final static int pageSize = 5000;

    private AtomicInteger pageNo = new AtomicInteger(startIndex);
    private AtomicInteger anotherPageNo = new AtomicInteger(startIndex);

    private int getNextPage_getAndIncrement (){
        return pageNo.getAndIncrement();
    }
    private int getNextPage_incrementAndGet (){
        return anotherPageNo.incrementAndGet();
    }

    public AtomicIntegerUsage () {
    }

    public static void main (String[] args) {
        AtomicIntegerUsage t = new AtomicIntegerUsage ();
        System.out.println (" First page is page with getNextPage_getAndIncrement :"+t.getNextPage_getAndIncrement());
        System.out.println (" First page is page with getNextPage_incrementAndGet:"+t.getNextPage_incrementAndGet());
    }
}


 First page is page with getNextPage_getAndIncrement :1
 First page is page with getNextPage_incrementAndGet:2






Java Thread Local Usage

    private ThreadLocal tl = new ThreadLocal(){
        protected synchronized Session initialValue() {
            return sessionForBatchLoading;
        }    
    };
    
    private Session sessionForBatchLoading = null;

    private void initializeSession () throws Exception {
        session = SessionFactory.getSession ();
        sessionForBatchLoading = factory.getSession ();
        tl.set(sessionForBatchLoading);
    }

    private void getOrder (int orderId) throws Exception {
        Session tlSession = tl.get ();
        tlSession.getItemFromDBWithId (orderId);
    }

*Session is not thread safe .


    private void startThreads (int threadCount) throws Exception {
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);

        for (int i = 0; i < threadCount; i++) {
            FetchTask task =  new FetchTask ();
            executor.submit (task);
        }

         executor.shutdown ();
    }

Tuesday, March 16, 2010

Too many open files error / opened file checker

#!/bin/bash
COUNTER=0
HOW_MANY=0
MAX=0
# do not take care about COUNTER - just flag, shown should we continue or not
while [ $COUNTER -lt 10 ]; do
    #run until process with passed pid alive
    if [ -r "/proc/$1" ]; then
        # count, how many files we have
        HOW_MANY=`/usr/sbin/lsof -p $1 | wc -l`
        #output for live monitoring
        echo `date +%H:%M:%S` $HOW_MANY
        # uncomment, if you want to save statistics
        #/usr/sbin/lsof -p $1 > ~/autocount/config_lsof_`echo $HOW_MANY`_`date +%H_%M_%S`.txt

        # look for max value
        if [ $MAX -lt $HOW_MANY ]; then
                let MAX=$HOW_MANY
                echo new max is $MAX
        fi
        # test every second. if you don`t need so frequenlty test - increase this value
        sleep 1
    else
        echo max count is $MAX
        echo Process was finished
        let COUNTER=11
    fi
done

Which type of java exception should be used ?

Unchecked exceptions :
  • represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."
  • are subclasses of RuntimeException, and are usually implemented using IllegalArgumentExceptionNullPointerException, or IllegalStateException
  • a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)
Checked exceptions :
  • represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
  • are subclasses of Exception
  • a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)
It is somewhat confusing, but note as well that RuntimeException (unchecked) is itself a subclass of Exception (checked).