hoist for var, let, const, function, function*, class

I have been playing with ES6 for a while and I noticed that while variables declared with var are hoisted as expected…

console.log(typeof name); // undefined
var name = "John";

…variables declared with let or const seem to have some problems with hoisting:

console.log(typeof name); // ReferenceError
let name = "John";

and

console.log(typeof name); // ReferenceError
const name = "John";

 

these variables cannot be accessed before they are declared. However, it’s a bit more complicated than that.

Are variables declared with let or const not hoisted? What is really going on here?

All declarations (var, let, const, function, function*, class) are hoisted in JavaScript. This means that if a name is declared in a scope, in that scope the identifier will always reference that particular variable:

x = "global";
(function() {
    x; // not "global"

    var/let/… x;
}());
{
    x; // not "global"

    let/const/… x;
}

This is true both for function and block scopes1.

The difference between var/function/function* declarations and let/const/classdeclara­tions is the initialisation.
The former are initialised with undefined or the (generator) function right when the binding is created at the top of the scope. The lexically declared variables however stay uninitialised. This means that a ReferenceError exception is thrown when you try to access it. It will only get initialised when the let/const/class statement is evaluated, everything above that is called the temporal dead zone.

x = y = "global";
(function() {
    x; // undefined
    y; // Reference error: y is not defined

    var x = "local";
    let y = "local";
}());

Notice that a let y; statement initialises the variable with undefined like let y = undefined;would have.

Is there any difference between let and const in this matter?

No, they work the same as far as hoisting is regarded. The only difference between them is that a constant must be and can only be assigned in the initialiser part of the declaration (const one = 1;, both const one; and later reassignments like one = 2 are invalid).

 

 

 

Advertisements

java synchronized on object, class and block

synchronized Blocks do have advantages over methods, most of all in flexibility because you can use other object as lock whereas syncing the method would lock the complete class.

Compare:

// locks the whole object
... 
private synchronized void someInputRelatedWork() {
    ... 
}
private synchronized void someOutputRelatedWork() {
    ... 
}

Vs.

// Using specific locks
Object inputLock = new Object();
Object outputLock = new Object();

private void someInputRelatedWork() {
    synchronize(inputLock) { 
        ... 
    } 
}
private void someOutputRelatedWork() {
    synchronize(outputLock) { 
        ... 
    }
}



More about synchronized method on object/class

Some code:

public class SOP {
    public static void print(String s)
    {
        System.out.println(s+"\n");
    }
}

public class TestThread extends Thread
{
    String name;
    SynchronisedDemo synchronisedDemo;
    public TestThread(String name,SynchronisedDemo synchronisedDemo)
    {
        this.synchronisedDemo = synchronisedDemo;
        this.name = name;
        start();
    }

    @Override
    public void run()
    {
        synchronisedDemo.test(name);
    }
}

public class SynchronisedDemo {
    public synchronized void test(String name)
    {
        for(int i=0;i<10;i++)
        {
            SOP.print(name + " :: "+i);
            try{
                Thread.sleep(500);
            }
            catch (Exception e)
            {
                SOP.print(e.getMessage());
            }
        }
    }

    public static void main(String[] args)
    {
        SynchronisedDemo synchronisedDemo = new SynchronisedDemo();
        new TestThread("THREAD 1",synchronisedDemo);
        new TestThread("THREAD 2",synchronisedDemo);
        new TestThread("THREAD 3",synchronisedDemo);
    }
}

Note: synchronized blocks the next thread’s call to method test() as long as the previous thread’s execution is not finished. Threads can access this method one at a time. Without synchronized all threads can access this method simultaneously.

When a thread calls the synchronized method ‘test’ of the object (here object is an instance of ‘Synchronised’ class) it acquires the lock of that object, any new thread cannot call ANY synchronized method of the same object as long as previous thread which had acquired the lock does not release the lock.

Similar thing happens when any static synchronized method of the Class is called.The thread acquires the lock associated with the class(in this case any non static synchronized method of an instance of that class can be called by any thread because that object level lock is still available).Any other thread will not be able to call any static synchronized method the class as long as class level lock is not released by the thread which currently holds the lock.

Output with synchronised

THREAD 1 :: 0
THREAD 1 :: 1
THREAD 1 :: 2
THREAD 1 :: 3
THREAD 1 :: 4
THREAD 1 :: 5
THREAD 1 :: 6
THREAD 1 :: 7
THREAD 1 :: 8
THREAD 1 :: 9
THREAD 3 :: 0
THREAD 3 :: 1
THREAD 3 :: 2
THREAD 3 :: 3
THREAD 3 :: 4
THREAD 3 :: 5
THREAD 3 :: 6
THREAD 3 :: 7
THREAD 3 :: 8
THREAD 3 :: 9
THREAD 2 :: 0
THREAD 2 :: 1
THREAD 2 :: 2
THREAD 2 :: 3
THREAD 2 :: 4
THREAD 2 :: 5
THREAD 2 :: 6
THREAD 2 :: 7
THREAD 2 :: 8
THREAD 2 :: 9

Output without synchronized

THREAD 1 :: 0
THREAD 2 :: 0
THREAD 3 :: 0
THREAD 1 :: 1
THREAD 2 :: 1
THREAD 3 :: 1
THREAD 1 :: 2
THREAD 2 :: 2
THREAD 3 :: 2
THREAD 1 :: 3
THREAD 2 :: 3
THREAD 3 :: 3
THREAD 1 :: 4
THREAD 2 :: 4
THREAD 3 :: 4
THREAD 1 :: 5
THREAD 2 :: 5
THREAD 3 :: 5
THREAD 1 :: 6
THREAD 2 :: 6
THREAD 3 :: 6
THREAD 1 :: 7
THREAD 2 :: 7
THREAD 3 :: 7
THREAD 1 :: 8
THREAD 2 :: 8
THREAD 3 :: 8
THREAD 1 :: 9
THREAD 2 :: 9
THREAD 3 :: 9

Generify class and method

To generify a class, declare the type directly after the class name:

public class NaturalNumber<T extends Integer> {

    private T n;

    public NaturalNumber(T n)  { this.n = n; }

    public boolean isEven() {
        return n.intValue() % 2 == 0;
    }

    // ...
}

To Generify a method signature (return type), declare the class access modifier:

    
    public static <T extends Status> Status getStatusByInternalLabel(Class<T> c, String internalLabel){
        if(!c.isEnum() || internalLabel == null){
            return null;
        }
        Status result = null;
        Object[] objects = c.getEnumConstants();
        for (Object o : objects){
            if(internalLabel.equals(((Status)o).getInternalLabel())){
                 result = (Status)o;
            }
        }
        return result;
    }

To Generify a method parameter, declare before the parameter:

    public static  List statusEnumsInternalLabelToSortedList(Class<? extends Status> c){
        if(!c.isEnum()){
            return null;
        }
        Object[] objects = c.getEnumConstants();
        List result = new ArrayList();
        for (Object o : objects){
            result.add(((Status)o).getInternalLabel());
        }
        Collections.sort(result);
        return result;
    }

multi level css class selection

div.high>div.middle>div.low {
    border: 1px solid #a8a8a8;      
}

That means “a div with a class of low, which is a child of a div with a class of middle, which is a child of a div with a class of high”.

<div class=”high”>

<div class=”middle”>

<div class=”low”>

</div>

</div>

</div>

Java and tomcat class loader, priority & hierarchy

Java class loader hierarchy

We have 3 main class loader :

  • Bootstrap class loader, called primordial class loader. It’s a part of the JVM., and is responsible for loading classes from the core Java package (java.lang, java.util etc.) These classes are found in JAVA_HOME/jre/lib/rt.jar.
  • Extension class loader. It monitors the JAVA_HOME/jre/lib/ext folder and load the existing jars.
  • System class loader. It monitors the folders and Jars which can be find in the classpath.

An important point is that a class loader can only see the class locations that are above it in the hierarchy. So a class loaded from Extension class loader can’t see a class from the class path.

Tomcat / java EE hierarchy

For security reason, each web app must use its very own class loader (you don’t want to share any class with another malicious application)
During startup, tomcat neutralize the System class loder by clearing the classpath.
It also changes the endorsed directory to point to CATALINA_HOME/endorsed.
Doing so, the class-loader hierarchy is reversed:

  • Tomcat internal class loader. Loads classes for tomcat internal code. Web applications can’t use this class loader.
  • Web application class loader. Loads classes from the WEB-INF/classes (first) and WEB-INF/lib for a webapp
  • Shared class loader. Loads classes from the folder specified in catalina.properties. Theses classes are visible only to all web apps.
  • Common class loader. Loads classes from CATALINA_HOME/lib (all web apps + tomcat: servlet-api.jar, jasper.jar, coyote.jar, jsp-api.jar etc.)
  • System class loader: Loads classes from the classpath, but the classpath is truncated by tomcat, so it doesn’t do anything except looking for CATALINA_HOME/bin/bootstrap.jar (tomcat startup), tomcat-juli.jar (logging) and tools.jar (for the jsp compiler).
  • Extention class loader (JAVA_HOME/jre/lib/ext)
  • Bootstrap class loader
  • Endorsed Standards Override Mechanism (the Endorsed Standards Override Mechanism lets you place overrides to certain classes (CORBA and JAXP classes) in the JAVA_HOME/lib/ endorsed folder. The Bootstrap loader will then load these preferentially over any classes that it might otherwise find. For details on this mechanism, see http://java.sun.com/j2se/1.5.0/docs/guide/standards/, Source : Tomcat 6 developer’s Guide, by Damodar Chetty)

When you try to load a class in a tomcat webapp, your default classloader first delegate to the standard class loader hierarchy :

  • the bootstrap serves up core classes.
  • extension loader : classes held within any installed extensions jar.
  • system class loader : catalina startup classes as well as supported classes.

If the class can’t be found, the webapp looks within its own repositories

  • from /WEB-INF/classes folder
  • from /WEB-INF/LIB/*.jar

If the class is still not found, the webapp delegate to it’s parent classloaser :

  • from %CATALINA_HOME%/lib/*.jar (common to all webapps, and internal tomcat classes)
  • the shared class loader : serves up classes that are common across all web appart within a given host.

More details on CLASS LOADER and how class loader WORKS

FROM HERE

The Java 2 delegation model cannot be followed in all situations. There are cases in which ClassLoaders have to diverge from the Java 2 model. For instance, the servlet specification recommends (section 9.7) that a Web application ClassLoader be implemented so that classes and resources packaged in the Web application archive are loaded in preference to classes and resources residing in container-wide JAR files. To meet this recommendation, a Web application ClassLoader should search for classes and resources in its local repository first, before delegating to a parent ClassLoader, thus deviating from the Java 2 delegation model. This recommendation makes it possible for Web applications to use different versions of classes/resources than those being used by a servlet container. For example, a Web application might be implemented using features available in a newer version of an XML parser than the one being used by a servlet container.

A Web application ClassLoader that meets the recommendation of the servlet specifications can be implemented by overriding the loadClass method of the java.lang.Classloader class. The loadClass method of such a custom ClassLoader may look similar to

 public Class loadClass(String name)throws ClassNotFoundException
 {    
    //check if the class is already loaded
    Class loadedClass = findLoadedClass(name);
    if (loadedClass == null) {
     //search for class in local repository before delegating
     .......      
     //if class not found delegate to parent
     loadedClass = this.getClass().getClassLoader().loadClass(name);
    }
    return loadedClass;
}

FROM HERE

java OOP basic vocabularies

What is a Class?

Class is a template for a set of objects that share a common structure and a common behavior.

What is an Object?

Object is an instance of a class. It has state,behaviour and identity. It is also called as an instance of a class.

What are the core OOP’s concepts?

Abstraction, Encapsulation,Inheritance and Polymorphism are the core OOP’s concepts.

What is meant by abstraction?

Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. Its the process of focussing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model.

What is meant by Encapsulation?

Encapsulation is the process of compartmentalising the elements of an abtraction that defines the structure and behaviour. Encapsulation helps to separate the contractual interface of an abstraction and implementation.

What is meant by Inheritance?

Inheritance is a relationship among classes, wherein one class shares the structure or behaviour defined in another class. This is called Single Inheritance. If a class shares the structure or behaviour from multiple classes, then it is called Multiple Inheritance. Inheritance defines “is-a” hierarchy among classes in which one subclass inherits from one or more generalised superclasses.

What is meant by Polymorphism?

Polymorphism literally means taking more than one form. Polymorphism is a characteristic of being able to assign a different behavior or value in a subclass, to something that was declared in a parent class.

What is an Abstract Class?

Abstract class is a class that has no instances. An abstract class is written with the expectation that its concrete subclasses will add to its structure and behaviour, typically by implementing its abstract operations.

What is an Interface?

Interface is an outside view of a class or object which emphaizes its abstraction while hiding its structure and secrets of its behaviour.

What is meant by Binding?

Binding denotes association of a name with a class.

What is meant by static binding?

Static binding is a binding in which the class association is made during compile time. This is also called as Early binding.

What is meant by Dynamic binding?

Dynamic binding is a binding in which the class association is not made until the object is created at execution time. It is also called as Late binding.