Thursday, 26 July 2018

Type based dependancy injection in Scala

As a developer when we start bootstrapping project development, we always think about some awesome Dependancy Injection (like google Guice, Spring etc.).
It will inject required object for us and will take care of object creation.

But what if compiler will to same job of dependancy injection for you instead of depending other heavy framework ?

Exactly we can achieve decency injection using  implicit in scala.

Example,
Lets say we want inject UserDao into service class 

case class User(name: String, id: Int)

trait UserDao {
  def getAll(): List[User]
}

class MongoUserDao extends UserDao {
  override def getAll(): List[User] = List.empty[User]
}

object UserDao {
  implicit val userDao: UserDao = new MongoUserDao
}

class UserService(implicit userDao: UserDao) {
  
}

As shown in above code, compiler will find out implicit value for userDao in its companion object.
We don't need external DI framework.















Wednesday, 20 September 2017

Learning IntelliJ IDE (Notes)

This blog regarding IntelliJ IDE setup.
Note :- If you find preference  then please consider setting on Microsoft window 


Installation 
1) Download & Install Java 8
2) Add java and javac to path 
3) Download IntelliJ IDE and install it ( Accept Default) do not install plugin any.

How to update ?
On Welcome window 
Configuration -> Check for update

How to set Default Project Settings ?
Go to 
Configure -> Project Default -> Project Structure

SDK Setup (In Configure -> Project Default -> Project Structure)
Click on New , add JDK folder (Not bin) 

Language Level (In Configure -> Project Default -> Project Structure)
Select drop down value 

How to add common Library to all project ?
Got to
Configure -> Project Default -> Project Structure -> Select Library

How to show line number in Editor Window ?
Configure -> Preference -> Editor -> Appearance -> check box Show line number


How to change font ?
Configure -> Preference -> Editor -> Font 

How to create project ?
On Welcome window 
Create New Project -> select option depends on plugin 
Short Cut ( Open Project Window  Alt + 1 /  cmd +1 )

How to find file in project ?
Open Project Window -> Then click Scroll from Window on Project window 
Project window has different scope

How to spread out empty package ?
Select gear icon on project window -> Hide Empty Middle Package 

Project Structure 
About .idea folder 
  • Has project related configuration.
  • All file need to be check in except following 
    • workspace.xml , belongs to current user 
    • tasks.xml if present , belongs to current user 
About ProjectName.iml 
  • This is projects main configuration file, should be checked in.
  • It determines nature of project and location of project source control file.
About out dir
  • It contains compiled file. Not need to check in.
External Library 
  • Contains jar , Not need to check in.
How to get online help regarding window? 
press F1 window , it will open url in browser 

How to add javaDoc ?
File -> Other Settings -> Default Project Structure -> SDK -> Documentation Path -> +
(Shift + F1  to go online Doc Direct)

How to add jar explicitly ?
Two ways 
File -> Project Structure -> Libraries

2]  Add new dir in project , add jar in it.
Right click on jar then select add Library

How generate JavaDoc ?
Tools -> Generate JavaDoc

How package classes in jar ?
File -> Project Structure -> Artefact -> + 
   Then
Build -> Build Artifact

How to run Jar ?
java -jar JarName.jar

How to Integrate GIT ?
1] Download GIT
Then 
VCS -> Enable Version Control  -> Select Git

How to open Different tool window ?
View -> Tool Window 

What is Gist ?
Awesome way to share code to public on GitHub.

How to create java method in scala ?
Just copy and paste, Intellij convert it automatically.

Friday, 14 April 2017

Too many open files (java.io.IOException: Cannot run program "chmod": error=24)

One week ago, on production we got java.io.IOException: Cannot run program "chmod": error=24 Too many open files.

Cause
         Basically we are copying files form Zip file to a folder on user action. And  we got one zip which has 15000 files in it.  we  open stream of input file and  output file , and copying from one stream to output file stream. Bad luck we forgot to close these streams (two stream, Input and Output for every file in Zip) . Ultimately there are 15000 * 2 = 30000 file descriptor is opened by single process.

Debug
         After some investigation we found, we have limit on number of File descriptor open by single process on production machine (Suse Linux).  The system command ulimit is great usefully. We have found configuration in file ~/etc/security/limits.conf .

We have found following setting in limits.conf file
* hard nofile 100000

* soft nofile 100000

Which indicate max and min number of file descriptor open by single process. But as per code we have opened 30000 file descriptor and this how we got Exception.

Solution

  • First and obvious solution is close stream after task done.
  • Second is to increase no. of file descriptor per process, which is not accepted by our Linux administrator. 
Java(1.7) Try with Resource Come in Handy to Auto close resource 
  • Best way to use java 1.7 new feature, try resource with which will close input stream, we don't have to close it manually.
  • Also it suppress any Exception accord during resource close. 

Sunday, 5 February 2017

Object Escape

This issue tensed all of my team mates for almost 10 days in production. For me just luck to identified and fixed in production. It was very difficult for us (40 developer) to reproduce it.
Hope this may helpful to others too.


Object Escape
     Object is said to be escaped, when it published before it not supposed to publish.
Publishing object means, make it available outside its scope.

Object is constructed by calling its constructor, but object is available before completion of constructor.


Lets look at following example, how class B is escaped.

Class A {
   public B b;
}

Class B {
   B(A a) {
      a.b = this;
      //Some other Operation
   }
}

public static void main(String[] args) {
   A a =  new A();
   B b = new B(a);
   // Object is b escaped
   //Some other thread can get B value before it constructor done
   // By calling a.b
}

Thumb rule is do not escape this reference from constructor.
Class B can broken if multiple thread is using A reference, can cause damage, usually not reproducible.

One of Safest Way avoid Object Escaping is to use factory method as shown below

class B {
   private B() {
   }

   public static B newInstance(A a) {
      B b = new B();//Constructor is completed
      a.b = b;
   }
}


Tuesday, 17 January 2017

UTF-8 with and without BOM issue



What Client want ?
             We have client which generate tones of report from project data in csv format for their BI(Business Intell) group.
File downloaded form server is encoded with UTF-8 without BOM (Byte Order Marker), that is fine and also stranded way. A standard saying is do not add BOM for UTF-8.
        But when same report file(.csv) is opened with MS Excel, it is not able to detect encoding of file because absence of BOM for UTF-8, and French character in file shows some random symbol. 

What we did ? 
We told them to open same file notepad++, because it detect the encoding and mark encode to UTF-8-BOM so it can open in Excel with proper encoding for special character. That is working fine and also good solution. 

What Client Replied ?
Client replied that they dont want open same file notepad++, instead it should open in Excel with correct encoding.

This is the story to dig up little into BOM (Byte Order Marker)
and  JVM s UTF-8 behavior 

What JVM Expect for UTF-8 Encoding ?
Whenever you read file using java with UTF-8, JVM is not excepting BOM character at starting of InputStream. If their is any BOM character present, JVM consider it as data of file. 
JVM not expecting BOM for UTF-8, which standard from UNICODE    

        Finally we have added BOM for UTF-8 encoding for file. And removing BOM character while reading the file. This is fix we have given to client.
        But may be in future client will come to us saying that they have one tools which consumes csv format data and while reading data,tool getting weird character at staring of file. Which is because client tool expecting file with UTF-8 encoding without BOM and tool considering BOM Character as data of input file.

But client is client, nobody beat them. 

Lazy Intialization (From Effective Java)

Most common said is to avoid lazy initialization if not required.
Lazy initialization play an important while performance is key.
As mentioned in effective java, there are two ways to do better lazy initialization.
  • Double checked Lock (For Instance Field)
  • Lazy Initialization holder class Idiom (For static field)
 Double checked Lock (For Instance Field)
                   
        In simple word, avoid synchronization on whole getter method, instead of that first check for null or default value(In case of primitives) and if required initialization then only use synchronization.
Following example depict simple use of double checked lock

private volatile FiledType filed;
FiledType getFiledType() {
    FiledType result = filed; //Use at least once pre Initialized 
    if (result == null) { // First check (No locking)
        synchronized(this) {
            if (result == null) { //Second checking (With locking)
                result = filed = computeFieldValue();
            }
        }
    }
    return result;
} 


Lazy Initialization holder class Idiom (For static field)
           It is also called as initialization on demand holder class idiom.
It guarantee that a class will not be initialized until it used(JLS 12.4.1).
Following code depict the same:-

//Lazy initialization holder class idiom for static filed initialization
private static class FiledHolder {
    static final FiledType filed =  computeFieldValue();
}
FiledType getFiledType() {
    return FiledHolder.filed; //Here class is initialized
}



Monday, 24 October 2016

Why Scala ?

As in my daily job all of my colleague ask me why scala ? 

Every time me telling them few things about scala, which I remember at that time, so finally I'm collecting  reason why scala ?
I will go adding into list, as I get know more Why Scala.

  • Mix of Functional and OO Programming
  • Strongly typed 
  • Strong Integration with Java
  • JVM Language
  • Rich collection API
  • Awesome syntax
  • REPL (Experient Orient Development)
    • Read 
    • Eval
    • Print
    • Loop