Wednesday, April 12, 2017

Useful git aliases

alias ga='git add'
alias gp='git push'
alias gl='git log'
alias gs='git status'
alias gss='git status -s'
alias gd='git diff'
alias gdc='git diff --cached'
alias gcm='git commit -m'
alias gcam='git commit -am'
alias gb='git branch'
alias gco='git checkout'
alias gra='git remote add'
alias grr='git remote rm'
alias gpu='git pull'
alias gcl='git clone'
alias gundo='git clean -f; git checkout .'

Sunday, November 08, 2015

Atomicity, Visibility & Ordering

Atomicity

If an operation comprising of set of actions is either all done or not at all i.e. it is indivisible, then its an atomic operation. 
To ensure atomicity:

  • Use atomic types defined in java.util.concurrent.atomic package that support atomic operations on single variables
  • Use synchronized blocks or methods to wrap all steps of an operation


Visibility

Visibility deals with whether changes made to a shared object/value are visible to other threads or not.

The compiler may optimize the access to a variable by storing it in the cache for the thread and thus any writes to the variable from another thread are not visible.

To ensure visibility:

  • The variable can be declared as volatile which forces the compiler to always read/write variable value from memory
  • Access the variable from within a synchronized block thus making sure that the compiler reads/writes the variable from memory when entering/leaving the synchronized block.


Ordering

Ordering refers to the order of execution of discrete instructions of an operation. Specifically in a multi-threaded environment, the manner of interleaving of instructions could lead to unexpected outcomes. This is referred to as race-condition.

Refer to the below article for more details on these topics:


Wednesday, September 10, 2014

Why Scala?

Of late, there has been a tremendous surge in interest for programming in Scala. Here are some of the reasons why people are choosing to program in Scala.


  • Java/JVM compatible
    • Runs on the JVM
    • Can reuse Java libraries
  • Concise code 
    • Less boiler plate code
    • Type inference
  • Type system
    • Statically typed
    • Rich type system
  • Supports OOP style
    • Mixin composition - traits
    • Companion objects (Singletons tied to types)
  • Supports Functional Programming style
    • Functions are first class values
    • Function literals
    • Emphasis is on using vals, immutable objects, functions without side-effects
  • Is scalable
    • User defined types
    • User defined operators
    • User defined control structures
    • Can be used to write scripts
    • Can be used to write large applications

Friday, March 07, 2014

MySQL Reference


Useful mysqladmin commands

1. Get MySQL version
[root@host]# mysqladmin --version
2. Post MySQL installation, the root user password is blank. To set the password, use the below command:
[root@host]# mysqladmin -u root password "new_password";
3. Create database
[root@host]# mysqladmin -u root -p create TUTORIALS
Enter password:******
4. Drop database
[root@host]# mysqladmin -u root -p drop TUTORIALS
Enter password:******


Adding new user

root@host# mysql -u root -p
Enter password:*******
mysql> use mysql;
Database changed

mysql> INSERT INTO user 
          (host, user, password, 
           select_priv, insert_priv, update_priv) 
           VALUES ('localhost', 'guest', 
           PASSWORD('guest123'), 'Y', 'Y', 'Y');
Query OK, 1 row affected (0.20 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 1 row affected (0.01 sec)

mysql> SELECT host, user, password FROM user WHERE user = 'guest';
+-----------+---------+------------------+
| host      | user    | password         |
+-----------+---------+------------------+
| localhost | guest | 6f8c114b58f2ce9e |
+-----------+---------+------------------+
1 row in set (0.00 sec)
or
root@host# mysql -u root -p password;
Enter password:*******
mysql> use mysql;
Database changed

mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    -> ON TUTORIALS.*
    -> TO 'zara'@'localhost'
    -> IDENTIFIED BY 'zara123';

Remember to FLUSH PRIVILEGES after doing the above!!


Administrative commands

# USE <database>;
# SHOW DATABASES;
# SHOW TABLES;
# SHOW INDEX FROM <tablename>;


Storage Engines

mysql> SHOW ENGINES\G
*************************** 1. row ***************************
 Engine: MyISAM
Support: DEFAULT
Comment: Default engine as of MySQL 3.23 with great performance
*************************** 2. row ***************************
 Engine: MEMORY
Support: YES
Comment: Hash based, stored in memory, useful for temporary tables
*************************** 3. row ***************************
 Engine: InnoDB
Support: YES
Comment: Supports transactions, row-level locking, and foreign keys
*************************** 4. row ***************************
 Engine: BerkeleyDB
Support: NO
Comment: Supports transactions and page-level locking
*************************** 5. row ***************************
 Engine: BLACKHOLE
Support: YES
Comment: /dev/null storage engine (anything you write to it disappears)
...

CREATE TABLE t (i INT) ENGINE = INNODB;
CREATE TABLE t (i INT) TYPE = MEMORY;
The older term TYPE is supported as a synonym for ENGINE for backward compatibility, but ENGINE is the preferred term and TYPE is deprecated.
SET storage_engine=MYISAM;
SET table_type=BDB;

Miscellaneous

1. Get table status such as type of storage engine etc

# SHOW TABLE STATUS;
2. Get server meta-data

CommandDescription
SELECT VERSION( )Server version string
SELECT DATABASE( )Current database name (empty if none)
SELECT USER( )Current username
SHOW STATUSServer status indicators
SHOW VARIABLESServer configuration variables





Wednesday, January 29, 2014

Static factory methods vs Factory pattern

Many of us are familiar with the use of static factory methods for object creation. However, there is quite a bit of confusion as to whether such static factory methods are the same as the factory pattern. Let me attempt to explain the difference between the two here.

Static factory method
A static factory method also known as named constructor is employed either in place of or in addition to traditional constructors for creating objects of the class. 

The advantages of using static factory methods are:

  1. Meaningful names for constructors
  2. Choice of creating new object or returning existing one (Ex: used in singletons)
  3. Can return sub-class objects

Now, static factory method has nothing to do with the Factory pattern. In case of factory pattern, one or more factory methods are defined in a factory class and are used to create objects of multiple possibly unrelated types.

Factory pattern

This pattern hides the object creation logic while providing a well defined interface for object creation.



Friday, January 17, 2014

Double checked locking optimization

Double checked locking aims to improve performance by reducing the need to acquire a lock by checking for the locking criteria first without acquiring the lock. Subsequently, if the lock is acquired, the locking criteria is checked again in order to ensure thread-safe code.

The locking criterion variable needs to be volatile for this to work correctly. If it not volatile, the compiler might optimize access to the variable thus allowing for it to contain an older value when the locking criterion check is made.

This technique is generally used in Singleton definition.

Example
public final class MySingleton implements Cloneable {
  private static volatile MySingleton instance = null;  
  
  private MySingleton() {
  }

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

Wednesday, January 15, 2014

Singletons in Java

As developers, we all have heard of Singletons. It would not be an exaggeration to state that it is the most popular design pattern. Having said that, what exactly is a Singleton?

A class that can only be instantiated only once is referred to as a Singleton.

In order to design a Singleton class, the following rules should be adopted:
  • Private constructors
    • This prevents creating objects of the class at will and ensures that object creation can only be done by code inside the class
    • It also prevents sub-classing
  • Class should be final
    • This prevents sub-classing
    • It also makes it explicit to the developer that the class cannot be sub-classed
  • Private static Object reference 
    • This is to store the reference to the singleton
    • Should be static
    • Should be private
    • Should be volatile
  • Static method that returns the singleton reference
    • Should be static
    • Should be public
    • Should be synchronized. This is to ensure that the method is thread-safe and a single object is created even in multi-threaded scenarios
    • Create object if not created
    • Return object reference
  • Prevent cloning
    • Implement Cloneable interface and throw the CloneNotSupportedException
    • This prevents cloning of the singleton

Example 1:
public final class MySingleton implements Cloneable {
  private static volatile MySingleton instance = null;
  
  private MySingleton() {
  }

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

  protected Object clone() throws CloneNotSupportedException {
      throw new CloneNotSupportedException();
  }
}

Approach II
Another approach is to create and assign the object to the static reference variable in the definition itself. Since, static members are initialized only once during class loading, it obviates the need to serialize calls to the static method which returns the singleton.

Example 2:
public final class MySingleton {
  private static MySingleton instance = new MySingleton();
  
  private MySingleton() {
  }

  public static MySingleton getInstance() {
      return instance;
  }  

  protected Object clone() throws CloneNotSupportedException {
      throw new CloneNotSupportedException();
  }
}

References
http://www.javaworld.com/article/2073352/core-java/simply-singleton.html

Wednesday, January 08, 2014

Exception handling v/s returning status codes - which is better?

I am sure that as a programmers we would have definitely pondered how best to report errors. Let us consider the available options:
  1. Return special values indicating the occurrence of error (or)
  2. Throw exceptions 
The first approach is the only method possible in older generation languages such as C where as exceptions are available in the newer languages such as Java, Python etc.

Exceptions are much superior mechanism for reporting errors as compared to returning status codes. Why that is so is enumerated below:
  • Exceptions cannot be ignored unlike status codes - As checking for status code is not mandatory, it is very common for developers to ignore the return values of methods. This implies that the error is not reported when it occurred causing the application to fail at a later point in code thus making the debugging that much harder. Exceptions on the other hand propagate up the calling stack until a matching handler is found or is caught by the runtime in the absence of a matching handler in code usually causing the application to fail. Thus an error reported via exceptions is always reported.
  • Sometimes returning status codes is not an option
    • Certain constructs like constructors do not return anything, so one cannot use status codes to report errors. 
    • In case of operator overloading which are basically implicit method calls, it is again not possible to return status codes indicating error
  • Exceptions carry context unlike status codes - When an exception is caught, the entire stack trace is made available starting from the point where it occurred. 
  • Exceptions can contain more descriptive error messages unlike status codes - Typically, the error messages reported via exceptions carry more information that what is possible to convey by just a error code.
    • For example, in a readFile() method, if the file is not found it might return a status code say -2 indicating that the file was not found. The same error when reported via a FileNotFoundException can be coded to contain a more descriptive message such as "File /tmp/abc.txt not found" 
  • Unlike exceptions, checking for errors clutters up the business logic - As multiple error code returns are possible, the error checking logic becomes tedious and often overshadows the actual business logic. Exceptions on the other hand result in much cleaner code as error handling can be kept separate from the business logic.
Caveats
Having said the above, there are cases where it is not appropriate to use exceptions
  • Exceptions should NOT be used as part of normal flow - Do not use exceptions to report any of the possible normal states of an operation. In such scenarios, convey the status of the operation by returning appropriate status code. Exception handling is expensive and should only be used to handle exceptional/abnormal conditions
References

Friday, January 03, 2014

Java Annotations

What are Annotations?
Annotations are basically syntactic meta-data that can be applied to packages, classes, methods, variables & parameters. 

Purpose
Annotations serve several purposes such as...
  • Provide extra information to the compiler
    • @Override
    • @SuppressWarnings
    • @Deprecated
  • Reduce boiler plate code
    • See project LomBok
    • AOP as in Spring AOP
    • Replacement for marker interfaces
  • Used by frameworks to glue user defined classes together into an application instead of specifying the same in an external XML configuration file
    • Spring
  • Provide information to be used at run-time 

Examples
Annotations can have elements which have values
@Author(name="kirk",  date="1/1/2014")

If annotations have a single element named value, it can be omitted as shown below:
@SuppressWarnings("unchecked")

If annotations have no elements, then the braces can be omitted as well:
@Override





Saturday, December 28, 2013

Java Reflection

Reflection in Java is a feature that makes it possible to inspect classes, interfaces, methods at run-time without knowing the names of classes, interfaces, methods at compile-time. It is also possible to create objects, invoke methods, get/set field values using reflection.

References
Java Reflection Tutorial by Jakob Jenkov
Java Reflection API


Fear leads to Anger, Anger leads to Hate, Hate leads to Suffering

"Fear leads to Anger, Anger leads to Hate, Hate leads to Suffering."
Master Yoda, Star Wars

“Anger is an acid that can do more harm to the vessel in which it is stored than to anything on which it is poured."
― Mark Twain

"Holding anger is a poison. It eats you from inside. We think that hating is a weapon that attacks the person who harmed us. But hatred is a curved blade. And the harm we do, we do to ourselves."
― Mitch Albom, The Five People You Meet in Heaven

“Men in rage strike those that wish them best.”
― William Shakespeare

The intoxication of anger, like that of the grape, shows us to others, but hides us from ourselves.
CHARLES CALEB COLTON, Lacon

When your rage is choking you, it is best to say nothing.
OCTAVIA E. BUTLER, Fledgling

Whatever's begun in anger ends in shame.
BENJAMIN FRANKLIN, Poor Richard's Almanack, 1734

To be angry is to revenge the fault of others upon ourselves.
ALEXANDER POPE, "Thoughts on Various Subjects"

Speak when you are angry and you will make the best speech you will ever regret.
AMBROSE BIERCE, The Devil's Dictionary

An angry man is always a stupid man.
CHINUA ACHEBE, Anthills of the Savannah

Anger glances in the breasts of wise men; but rests in the bosom of fools.
WELLINS CALCOTT, Thoughts Moral and Divine

I was angry with my friend:
I told my wrath, my wrath did end.
I was angry with my foe:
I told it not, my wrath did grow.
WILLIAM BLAKE, Songs of Experience

“The best fighter is never angry.”
― Lao Tzu

Happiness comes from within, not without

“Happiness depends upon ourselves.”
“Folks are usually about as happy as they make their minds up to be” 

“All happiness depends on courage and work.”

“Happiness is having a large, loving, caring, close-knit family in another city.”

“Of all forms of caution, caution in love is perhaps the most fatal to true happiness.”

“Happiness in intelligent people is the rarest thing I know.” 

“Happiness is when what you think, what you say, and what you do are in harmony.” 

Friday, December 27, 2013

Java Collections

A Collection is an object that groups together several objects. The Java Collections framework comprises of...
  • Interfaces
  • Implementations
  • Algorithms

Interfaces & Implementations
The different collection implementations conform to one or more of the generic interfaces shown in the interface hierarchy below...
Interface Hierarchy

Some important Collection interface methods
  • size(), isEmpty()
  • add(), remove(), contains()
  • iterator(), toArray()
  • Bulk operations - addAll(), removeAll(), retainAll(), containsAll()
Bulk operations are so called because they operate on entire collections.

Set interface models the mathematical set abstraction. 
  • Duplicate elements are not allowed
  • No additional methods are defined in this interface
  • equals(), hashcode() methods can be used to compare different sets even though their implementations differ
  • Implementations
    • HastSet - hash table implementation (best performance for most scenarios)
    • TreeSet - Red-Black tree implementation
    • LinkedHashSet - hash table with a linked list running through it
List is an ordered collection
  • Positional access methods - get(), set(), add(), addAll(), remove(), indexOf(), lastIndexOf()
  • ListIterator<>, subList()
  • Implementations
Queue interface models the queue abstraction
  • Typically FIFO type of data structure (except in case of Priority Queues)
  • Two types of methods
    • Methods that throw exception on failure - add(), remove(), element()
    • Methods that return special value on failure - offer(), poll(), peek()
  • Implementations
Deque pronounced as deck is a double-ended queue. I like to think of it as a queue-stack hybrid
  • Permits operations at both ends of the queue
  • Two types of methods
    • Methods that throw exception on failure - addFirst/Last(), removeFirst/Last(), getFirst/Last()
    • Methods that return special value on failure - offerFirst/Last(), pollFirst/Last(), peekFirst/Last()
  • Implements the Queue interface - add(), remove(), offer()... are also available
  • Stack operations supported - push(), pop(), peek()
  • Implementations
Map is an object that maps keys to values. It models the mathematical function abstraction. 
  • No duplicate keys allowed
  • Methods - put(), get(), remove(), containsKey(), containsValue()
  • Collections views - keySet(), values(), entrySet()
  • Implementations
    • HastMap - hash table implementation 
    • TreeMap - Red-Black tree implementation
SortedSet maintains elements in ascending order or according to the order specified by the Comparator provided at creation time. Several additional methods are provided to take advantage of the ordering. Useful for modelling word lists, membership rolls etc

SortedMap maintains the keys in ascending order or according to the order specified by Comparator provided at creation time. Useful for modelling dictionaries, directories etc


Algorithms
Algorithms provide useful computations like sorting and searching over the elements of the collection. They are polymorphic and can be used across the different collection implementations.