Friday, May 25, 2012

Importance of a Mentor

We almost ignore the importance of a good mentor. We hop jobs seeking higher salary, bigger responsibilities, even when it sometimes means parting with great mentor. I have done such things. I do realize how much important a good mentor is in shaping one's career. I wish I can find one similar that I lost with my old job.

Monday, April 23, 2012

The Six Rules Jack Welch Lives By


The six rules are:
  1. Face reality as it is, not as it was or as you wish it to be.
  2. Be candid with everyone.
  3. Don’t manage, lead.
  4. Change before you have to.
  5. If you don’t have a competitive advantage, don’t compete.
  6. Control your own destiny, or someone else will.
Source:

Sunday, April 22, 2012

Technical ladder vs Management ladder

Never have I been so restless (maybe leaving apart the UK higher education days), one thought that keeps me awake all night -- whether to choose technical ladder or management ladder.

Coming from a technical background, I still enjoy programming, doing technical things. However, there is a small part of me which craves for management work, power to influence critical decisions. I enjoy leading and guiding a small team. I love to have bigger picture of work.

Hope I find some answer in coming years.


Wednesday, February 29, 2012

Java Nuggets


class Example implements Iterable<Integer>
{
    List<Integer> data = new LinkedList<Integer>();

    public Iterator<Integer> iterator()
    {
        return this.data.iterator();
    }
}

public class Main
{
    public static void main(String[] args)
    {
        Example ex = new Example();
        // Enhanced for loop for class that implements Iterable interface
        for (Integer i : ex)
        {
            System.out.println("Element " + i);
        }
    }
}

Sunday, February 26, 2012

SCJP

public class Main
{
    /**
    Thread.sleep() sends the current thread into the "Not Runnable" state for some
    amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread
    is currently in a synchronized block or method no other thread can enter this block
    or method. If another thread calls t.interrupt() it will wake up the sleeping thread.
    Note that sleep is a static method, which means that it always affects the current
    thread (the one that is executing the sleep method). A common mistake is to call
    t.sleep() where t is a different thread; even then, it is the current thread that
    will sleep, not the t thread.

    t.suspend() is deprecated. Using it is possible to halt a thread other than the
    current thread. A suspended thread keeps all its monitors and since this state is
    not interruptable it is deadlock prone.

    object.wait() sends the current thread into the "Not Runnable" state, like sleep(),
    but with a twist. Wait is called on a object, not a thread; we call this object the
    "lock object." Before lock.wait() is called, the current thread must synchronize on
    the lock object; wait() then releases this lock, and adds the thread to the "wait list"
    associated with the lock. Later, another thread can synchronize on the same lock object
    and call lock.notify(). This wakes up the original, waiting thread. Basically,
    wait()/notify() is like sleep()/interrupt(), only the active thread does not need a
    direct pointer to the sleeping thread, but only to the shared lock object.
     */

    /**
    A thread state. A thread can be in one of the following states:
    NEW
        A thread that has not yet started is in this state.
    RUNNABLE
        A thread executing in the Java virtual machine is in this state.
    BLOCKED
        A thread that is blocked waiting for a monitor lock is in this state.
    WAITING
        A thread that is waiting indefinitely for another thread to perform a particular action is
        in this state.
    TIMED_WAITING
        A thread that is waiting for another thread to perform an action for up to a specified waiting
        time is in this state.
    TERMINATED
        A thread that has exited is in this state.
        A thread can be in only one state at a given point in time. These states are virtual machine
        states which do not reflect any operating system thread states.
     */

    /**
     * @param args
     * @throws IOException
     * @throws InterruptedException
     */
    public static void main(String[] args) throws IOException, InterruptedException
    {
        Main main = new Main();
        main.createProcess();
        main.createThread();
    }

    // To prevent memory consistency issue
    // Due to thread (local) cache, a write from one thread may not reflect in other
    // Read of volatile variable that was modified by other thread reflects the changes
    private volatile int sharedResource;

    // Immutable objects (shared resource donot require synchronization)

    // 1. Don't provide "setter" methods — methods that modify fields or objects
    // referred to by fields.
    // 2. Make all fields final and private.
    // 3. Don't allow subclasses to override methods. The simplest way to do this is to
    // declare the class as final. A more sophisticated approach is to make the constructor
    // private and construct instances in factory methods.
    // 4. If the instance fields include references to mutable objects, don't allow those objects
    // to be changed:
    // 4.1. Don't provide methods that modify the mutable objects.
    // 4.2. Don't share references to the mutable objects. Never store references to external,
    // mutable objects passed to the constructor; if necessary, create copies, and store
    // references to the copies. Similarly, create copies of your internal mutable objects
    // when necessary to avoid returning the originals in your methods.

    private void createProcess() throws IOException
    {
        ProcessBuilder pb = new ProcessBuilder("mspaint");
        //set the process builder's working directory by passing the File to the directory() method
        pb.directory(new File("."));
        //add and remove environment variables
        Map<String,String> env = pb.environment();
        env.put("var1", "value");
        env.remove("var3");
        //start the sub process
        Process p = pb.start();
        //gets the output stream of sub process as input stream.
        p.getInputStream();
        //kill the process
        p.destroy();

        //older way before java 1.5
        Runtime r = Runtime.getRuntime();
        Process p1 = r.exec("mspaint");
    }

    private void createThread() throws InterruptedException
    {
        //start threadA
        Thread th1 = new ThreadA();
        th1.start();
        //start threadB
        Thread th2 = new Thread(new ThreadB());
        th2.start();
        // current thread (Thread.currentThread())waits until th2 thread is finished executing
        // never say (eternal wait)-- Thread.currentThread().join();
        // throws interrupted exception if interrupted while waiting
        th2.join();
        // Sleep so that Thread A and Thread B may run
        Thread.sleep(2000);
        //interrupt thread A which is sleeping for 10 seconds
        th1.interrupt();
    }
}

// Note that constructors cannot be synchronized — using the synchronized keyword
// with a constructor is a syntax error. Synchronizing constructors doesn't make sense,
// because only the thread that creates an object should have access to it while it is
// being constructed.
class ThreadA extends Thread
{
    public void run()
    {
        System.out.println("ThreadA running");
        this.sleepMethod();
    }

    private void sleepMethod()
    {

        // sleep does not releases lock (if inside synchronized method/block -- i.e has acquired monitor)
        // Sleep can be interrupted, t.interrupt()
        try
        {
            // sleep for 10 seconds
            Thread.sleep(10000);
        }
        catch (InterruptedException e)
        {
            System.out.println("Sleep was interrupted");
        }
        // If the thread has started, and was not in a sleep() or wait() method,
        // then calling interrupt() on it does not throw an exception. Instead it
        // sets the thread's interrupted flag. This flag can then be used as the
        // thread's stop flag.

        // clears interrupted flag
        //if (Thread.interrupted())
        //{
        //    System.out.println("I was interrupted!");
        //    e.printStackTrace();
        //}
        // Does not clear interrupted flag
        // if(Thread.currentThread().isInterrupted())
        // {
        //    System.out.println("I was interrupted!");
        //    e.printStackTrace();
        // }
    }
}

class ThreadB implements Runnable
{
    // synchronizes on class object i.e. this.getClass()
    // Static and object synchronized methods can run concurrent.
    private synchronized static void staticSynchronizedMethod()
    {
    }

    // The resource itself can be used as locking object to lock on
    // private List sharedList = new LinkedList();

    // The lock/monitor used for synchronization
    private Object lock = new Object();

    private synchronized void blockSynchronization() throws InterruptedException
    {
        // block synchronization.
        // Can have synchronization inside synchronization
        synchronized (this.lock)
        {
            while (true)// some contion
            {
                // wait can be called outside from outside synchronized block
                // however throws IllegalMonitorStateException
                // No way to find if its because of notify or timed out
                this.wait(1000);
            }
        }
    }

    // synchronizes on 'this' object itself
    private synchronized void methodSynchronization() throws InterruptedException
    {
        // wait can be interrupted, wait releases acquired lock
        // wrong way of doing - lock acquired for this object and waiting on lock object
        // Will throw IllegalMonitorStateException as it has not acquired lock
        this.lock.wait();
    }

    private void notifyMethod()
    {
        // acquire lock and then notify
        synchronized (this.lock)
        {
            // set some condition to true to inform waiting thread
            this.lock.notifyAll();
            //this.lock.notify();
        }
    }

    public void run()
    {
        System.out.println("ThreadB running");
    }
}
References:
http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html http://java.sun.com/docs/books/jls/second_edition/html/memory.doc.html http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html http://www.cs.umd.edu/~pugh/java/memoryModel/index.html http://forward.com.au/javaProgramming/HowToStopAThread.html http://jeremymanson.blogspot.in/2008/11/what-volatile-means-in-java.html http://www.javaspecialists.eu/archive/Issue056.html

Sunday, February 19, 2012

Java Nuggets


class A
{

}

class B extends A
{

}

public class Main
{

    public static void main(String[] args)
    {
        A a = new A();
        //A a = null;
        //Also check 
        //A.class.isAssignableFrom(cls);
        B b = new B();
        A ab = new B();

        if (a instanceof A)
        {
            System.out.println("a instanceof A - true");
        }
        else
        {
            System.out.println("a instanceof A - false");
        }

        if (a instanceof B)
        {
            System.out.println("a instanceof B - true");
        }
        else
        {
            System.out.println("a instanceof B - false");
        }

        if (b instanceof A)
        {
            System.out.println("b instanceof A - true");
        }
        else
        {
            System.out.println("b instanceof A - false");
        }

        if (b instanceof B)
        {
            System.out.println("b instanceof B - true");
        }
        else
        {
            System.out.println("b instanceof B - false");
        }

        if (ab instanceof A)
        {
            System.out.println("ab instanceof A - true");
        }
        else
        {
            System.out.println("ab instanceof A - false");
        }

        if (ab instanceof B)
        {
            System.out.println("ab instanceof B - true");
        }
        else
        {
            System.out.println("ab instanceof B - false");
        }

    }
}

Result:
a instanceof A - true
a instanceof B - false
b instanceof A - true
b instanceof B - true
ab instanceof A - true
ab instanceof B - true

Saturday, February 11, 2012

Motivation




Motivation



Three rules John Wooden believed in:

  1. Never be late. Start on time, end on time.
  2. Not one word of profanity.
  3. Never criticize a teammate.
Other take away:
  1. Never try to better someone else.
  2. Always try to learn from others.
  3. Never cease to be best you could be. 
  4. Never let what you cannot do...interfere with what you can do.
  5. Do not try to control that is not under your control, or you would lose control of things that you have control of.
  6. Do the best you are capable of. Things will work out as they should, as long as we do what we should.
  7. The journey is better than end.
  8. Have patience, Have faith.
  9. Reputation is what you perceive to be, Character is what you are.





Sunday, January 29, 2012

Motivation

 Daniel Ek, CEO, Spotify
Figure out what the top five most important stuff is, focus relentlessly on that and keep iterating. Less is more.

Dennis Crowley, CEO, FourSquare

Don’t let people tell you your ideas won’t work. If you have a hunch that something will work, go build it. Ignore the haters.

Sarah Prevette, Founder, Sprouter

Just do it. Get it out there, absorb the feedback, adjust accordingly, hustle like hell, persevere and never lose your swagger.

Sarah Lacy, CEO, PandoDaily

Follow your gut. it may be wrong, but you won’t regret it if you fail. You’ll regret it if you ignore your gut and fail.

Craig Newmark, Founder, Craigslist

Treat people like you want to be treated. Apply to customer service.

Gary Vaynerchuk, CEO, VaynerMedia

Do work for your customers, not for press or VCs. The end user is what matters long term.

Matt Mullenweg, CEO, Automattic

Only reinvent the wheels you need to get rolling.

Jason Goldberg, CEO, Fab.com

Pick one thing and do that one thing — and only that one thing — better than anyone else ever could.

 Alexis Ohanian, CEO, Reddit

Make something people want. Then give more damns than anyone else about it and you’ll make something they love.

Chris Brogan, President, Human Business Works

Buy @ericries’s book. Beyond that? Build a platform. This is the big year.

Matt Howard, CEO, ZoomSafer

Startup wisdom: The number one job of a CEO is to not run out of money.

Brian Wong, CEO, Kiip

Always be learning from others. Whenever you meet someone, you don’t want something from them, you want to learn from them.

Seth Priebatsch, Chief Ninja, SCVNGR and LevelUp

Something my dad taught me: Ask forgiveness, not permission!

Hooman Radfar, Founder, Clearspring

Give away the wins, own the loses. Your job is to curate greatness.

Alexa Hirschfeld, CEO, Paperless Post

Users and employees are key predictive indicators of a company’s success; press and investors generally months behind.
Reference:
http://gigaom.com/2012/01/28/corbett-15-things-ceos-want-you-to-know/

Sunday, January 1, 2012

Good Java Tutorial Websites

SCJP

package test;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.List;

// Annotation
@MyAnnotationType(version = 1.1, clients = { "Programs" })
class Main
{
    public void method1()
    {
    }
}

public class Main1 extends Main
{
    public static void main(String[] args)
    {
        Main1 m = new Main1();
        m.method1();
    }

    // Annotation provided by java
    // annotation tells the compiler to suppress specific warnings that it would otherwise generate.
    @SuppressWarnings({ "unchecked", "deprecation" })
    // annotation informs the compiler that the element is meant to override an element declared in a superclass.
    @Override
    // annotation indicates that the marked element is deprecated and should no longer be used.
    @Deprecated
    public void method1()
    {
        List l;
    }
}

// The filename should be named same as public class or interface
// meta annotation - annotation to annotation
@Documented
@Inherited
// public enum ElementType {
//    TYPE,         // Class, interface, or enum (but not annotation)
//    FIELD,        // Field (including enumerated values)
//    METHOD,       // Method (does not include constructors)
//    PARAMETER,        // Method parameter
//    CONSTRUCTOR,      // Constructor
//    LOCAL_VARIABLE,   // Local variable or catch clause
//    ANNOTATION_TYPE,  // Annotation Types (meta-annotations)
//    PACKAGE       // Java package
//  }
@Target({ ElementType.FIELD, ElementType.TYPE })
// public enum RetentionPolicy {
//    SOURCE,       // Annotation is discarded by the compiler
//    CLASS,        // Annotation is stored in the class file, but ignored by the VM
//    RUNTIME       // Annotation is stored in the class file and read by the VM
//  }
@Retention(RetentionPolicy.SOURCE)
// simple annotation type
@interface MyAnnotationType {

    public enum MyEnum {
        ONE, TWO, THREE
    };

    //Annotation declaration should start with an 'at' sign like @, following with an interface keyword, following with the annotation name.
    //Method declarations should not have any parameters.
    //Method declarations should not have any throws clauses.
    //Return types of the method should be one of the following: primitives,String,Class,enum,array of the above types

    // string type
    String author() default "n/a";

    // array type
    String[] clients() default { "Programs", "GUI", "TestJig" };

    // enum
    MyEnum update() default MyEnum.ONE;

    // double type
    double version() default 1.0;

}
References:
http://docs.oracle.com/javase/tutorial/java/javaOO/annotations.html
http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm
http://technicalmumbojumbo.wordpress.com/2008/01/13/java-custom-annotations/
http://www.ibm.com/developerworks/library/j-annotate2/index.html