Concurrency handling - Java vs Erlang

Some may say that you cant compare apples and oranges. That's true. (apples and oranges in here being Java and Erlang. From your preference pick which is which). But we can certainly put them into a salad, separately and compare the final taste.

Lets set some goals here.

  1. The main goal here is not to compare Java vs Erlang. It will be a separate issue and will need a separate approach.
  2. The goal will be to compare each ones concurrency aspects.
  3. Conduct the comparison to as deep as possible.
  4. If the comparison is too long, create another post and continue there. This is because Im free winging right now, so this may become lengthy. :)

Processes and threads

The terms process and thread can be interchangeable in software concurrency realms. Generally speaking process/thread is some component/things that are responsible to perform assigned tasks.

Generally a process has a memory space that is needed for its operations. For example lets say there is a process called A, is reading bytes from a socket. A's memory space may consists of the sockets identifier, if socket is writing data to a file, it needs to know that file descriptor, A may have some variables and data in his memory space.

A thread operates under a process. So a thread shares that process's memory. Everything in that process memory is accessible by the threads. Process can have multiple threads.

Good things: Threads are easy to create.
Why ?
A process needs its own memory space. So if you create 2 processes, somebody (your OS or JVM) has create/allocate/chunk another portion of memory. Since threads share the same memory as the process you don't need to create another memory chunk for each thread. Just create the thread and use it.

Bad things: Since multiple threads are accessing and operating on the same memory, they need to communicate and take turns when they access a common thing, lets say a variable/ file descriptor.

Java

Java follow processes and threads jargon. So in Java, we can create processes with ProcessBuilder (https://docs.oracle.com/javase/8/docs/api/java/lang/ProcessBuilder.html) objects and create threads with Thread (https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html) objects.

Java processes/threads are built by the JVM and has one to one mapping with OS processes and threads. And yes, Java has ways to communicate between threads when sharing memory. More later.

Erlang

Erlang does not has concept of threads. It only has processes which created with the Erang VM (EVM/ beam). Since these are not kernel level processes but VM level processes, are very very light weight and can spawn instantaneously. If using raw Erlang,we can use spawn(Module, Function, Args) (http://erlang.org/doc/getting_started/conc_prog.html) to create a proces. If we are using Erlang Open Telecom Platform we can use custom made very specific processes like gen_fsm, gen_server, gen_statem.

Erlang is a functional prog language and it has this principal called "Share Nothing". Since Erlang processes has no common memory, they can operate separately without any conflicts easily.


Share:

Internals of Java Virtual Machine

The purpose of the JVM is to load .class files and execute those .class files.

Lets say you have a A.java source file.
You can compile A.java  with javac utility provided by JDK/JRE.
Now you get A.class (may be multiple .class files depending on your A.java inclusions). A.class is a bytecode version. Meaning it is not the final assembly instructions to be executed by the CPU. Still JVM process hasnt started.



JVM starts when you run your bytecode files (A.class)

When you run your A.class with java utility an instance of JVM is attached with the running process.

In that JVM instance your .class files(Along with standard Java classes like Object, System, String) are loaded into Class Loader module in JVM.

Loaded class files are then fed into the Execution engine module (Before it is fed into Execution engine and after its being processed from class loader module, the related data is stored at runtime data area). To execute the instruction in the bytecodes this module has to transact with OS via native method calls.


Class Loader module


This does 3 things.
1. Load - This has sub class loading modules which loads system rt.jar files and additional .jar files and your .class files specified in CLASSPATH dir

2. Link - First it verifies that wheather all the bytecodes are according to the JVM specification. Then in the prepare process, for class variables (static) only memory is allocated(Not for instance variables ). Finally in resolve phase symbolic references in your bytecodes are translated into actual references.

3. Initialize - All the static variables are initialized here.

RT data areas


1. Method area - All the class level data is here (Reflection API, Static variables). This is also known as the permGen area. And By defualt 64 Megabytes are allocated to here. But as per you runtime requirements you can adjust this size allocated by the JVM instance. From Java 8 method area is moved to host operating system's memory area called metaspace.

2. Heap - This is where all the objects and its data are stored. Based on the runtime requirement you can adjust the heap size.

3.Program Counter (Register) - This is instruction list per thread.  Meaning you will have n counters of programs for n threads.

4. Java stacks - Stack frames are stored in here per thread. For local methods. 

Execution Engine


Interpreter - just like a traditional interpreter it interprets the required instructions that are needed to be called to native methods . This is aided by JNI (Java Native method interface, and Native method libs like .dlls .so s)

JIT compiler and hotspot profier -

Java code is normally distributed as bytecode, which is machine-independent pseudocode. (The same idea was previously used in UCSD-p system developed in the 70'ies.) The advantage of this is that the same application can be run in different processors and operating systems. In addition, the bytecode is often smaller than compiled application.
The disadvantage is that interpreting the code is slow compared to running compiled code. To solve this problem, JIT compiler was developed. JIT compiler compiles the code into machine code just before the code is executed. This speeds up the execution compared to interpreter, but additional time is spent for compiling every time the program is run. In addition, since JIT compiler must compile fast, it can not use complex optimization techniques that are used in static compilers.
Another approach is HotSpot compiling. It initially runs as interpreter, but then detects which routines are used most often and compiles only those. The advantage is that there is no initial delay due to the compiling. In addition, HotSpot compiler may do profiling during the execution and then issue stronger optimization for the most important routines. It may even gather information so that when you run the same application again and again, it will run faster and faster. More information about HotSpot compiling can be found from this article (tnx Pangea for the link).
Of course, instead of using JIT compiler, you could just use a static compiler to compile the bytecode for your machine. This allows full optimization and then you do not need to compile again every time you run the application. However, in phones and web pages, you often just execute the code (or applet) once, so JIT compiler may be a better choice.    from stackoverflow

Garbage collector - If there is no references in stacks are pointed to objects in heap, those objects are removed from the heap by garbage collector. This is a memory optimization technique by JVM. This and this are good resources to refer.  
Share:

Spring MVC - DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler


This is full exception thrown from the server.

javax.servlet.ServletException: No adapter for handler [Class name]     
The DispatcherServlet configuration needs to include a HandlerAdapter 
that supports this handler

Problem Overview

This is took me a while to figure this out with lot of readings in Spring docs.

In Spring MVC when there is a need to map request -> Handler objects we need to have Handler Mapping interface implmented.

This is in org.springframework.web.servlet as Spring uses servlet technology under the hood.

In the dispatcher-servlet you can have any handler mapping implemented.

But by default with dispatcher-servlet, BeanNameUrlHandletMapping and DefaultAnnotationHandlerMapping is included.

See for more details.


Solution

Since BeanNameUrlHandletMapping comes in default you dont need to override it again in the dispatcher.
If you have done it, simply remove and it works fine. And worked for me. :D 

PS

Since Spring 3.1 they have removed DefaultAnnotationHandlerMapping 
and introduced RequestMappingHandlerMapping






Share:

JSP FAQs

What is a JSP ?

JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pages based onHTML, XML, or other document types.
Basically it is html file with JAVA logic inside it with the extension of .jsp

.jsp  files (html + java code) = .php (html + php code) = .xhtml in .net (html + C# code or razor syntax)

How JAVA logic is inserted inside html markup?
<%@ page global attributes and imports %>
<%@ include file="jsp file location" %>
<%! Java functions to be exectued %>
<% Java code %>
<%=JAVA expression %>

How .jsp s are interpreted in a server ?

abc.jsp will be executed as a servelt named abc_jsp. So corresponding abc_jsp.class and abc_jsp.java file will be generated in a server folder to be executed.

Depending on the request (GET or POSt...) the following will be parsed within doGET() or doPOST() ...
  • All the html content will be rendered in printwriter.println("html content") statements.
  • All the Java codes will be executed as normal java  code.
  • Any Java functions decalred in <%! %> will be parsed outside doGET() or doPOST() 
Then the final HTML data will be sent to browser/client.

What are implicit objects in JSP page ?
Meaning you dont have to create references to some objects. In a jsp scope they are created for you.
request.attribute --> HttpServeletRequest objects
session.attribute --> HttpSession objects
application.attribute --> ServletContext objects

What is the role of PageContext class ?


This object is intended as a means to access information about the page while avoiding most of the implementation details.

This object stores references to the request and response objects for each request. The application, config, session, and out objects are derived by accessing attributes of this object.
  1. JSP Page – Scope: PAGE_CONTEXT
  2. HTTP Request – Scope: REQUEST_CONTEXT
  3. HTTP Session – Scope: SESSION_CONTEXT
  4. Application Level – Scope: APPLICATION_CONTEXT
for example,
without 
request.setAttribute("key","value");
session.setAttribute("key", "value"),
you can 
pageContext.setAttribute("key", "value", PageContext.SESSION_SCOPE);
pageContext.setAttribute("key", "value", PageContext.REQUEST_SCOPE);
Share:

Java Servlets FAQs


What is a servlet ?
Simply it means something that can extend a servers functionality.
(for example a servlet can be used to process DB queries or client request processing )

So servelts run in a server just like PHP and ASP.net and normally serverlets are deployed in a web container. So there can be many servlets in a web container.


What happens in a sevelts life cycle ?
3 Things actually.
  1. Init() - Container intialize a servlet. (Serveltconfig object is initially passed to this method)
  2. Service() - servlet handles the service. Decides doGET(),doPOST() or any appropriate method to execute. Normally servlet can handle any number of requests and each request run on a separate thread.
  3. Destroy() - Once the service is performed that servlet/thread instance is killed.
What describes the first view/page to load in a Java web application unless it is not configured in the web server ?
web.xml (deplyment descripter)in WebContent/WEB-INF

How a Java class becomes a servlet ?
Two things.
1. It should extend HttpServlet class (if the servelt is a type of HTTP coz there are other types of servelets as well which inherits from GenericServelt class)
2. it should contain proper annotations (or Servelt tags in web.xml for apps before JAVA 5)

What happens in a Servlet web project when the browser executes an URL ?

  1. Browser sends the url to Java server (Lets say www.example.com/webapplication1/randomservlet1 to wildfly/Jboss server or tomcat or anything)
  2. Jboss at example.com has multiple web applications. 
  3. Jboss get the url and sees that it belongs to webappplication 1
  4. Jboss creates 2 objects
    1. HttpServletRequest object - as inputs to servlet
    2. HttpServletResponse object -as outputs from servlets
  5. Jboss then sends these 2 objects to randomservlet1. (probably doGET() after reading web.xml)
  6. Then servelt does its job.
  7. If there is something to be sent back to browser it is included in the response object.
  8. Jboss renders what is in the response object and sends back to browser. 

How a servelt gets a value from url prameter from ?name=RobinHood
String name = response.getPrameter("name")
If it is a GET this will be executed in doGET()
If it is a POST this will be executed in doPOST()
If it is a HEAD this will be executed in doHAED() and so on...................

How object creation happens in Servlet application ?

  • HttpServletRequest, HttpServletResponse objects are created per connection (These are stateless)
  • Create HttpSession objects if we want to maintain the state (getSession() from request object per client/browser) 
  • Create ServletContext if you want to have persistand data across users/browser (setServeltContect() from request object)
  • HTTPServelt s are cerated in threads per connection




Share:

How to install Titanium Appcelerator on Linux (Ubuntu) ?

This question has been asked like lot of times in the internet and havent seen a solid answer or someone got this working. I had this problem for like 2 weeks and finally I managed to solve it. Meaning I have just installed Titanium 5.x on Ubuntu 15.10 successfully after like 2 weeks non-stop tedious attempts. I have seen this problem of Titanium forums and StackOverflow posts lot of times but again - NO SOLID ANSWER.

I cant guarantee the correctness of this solution but these are the steps I follow. 

Install JDK

This has to be 7 or 8 according to the official documentation.

Install Node.js

For linux node.js version has to be between 0.1x and 4.2x. These are the supported version according to the documentation. The latest version of node is higher than this and there is no gurantee that it will work. So I also downgraded to  4.0.0 version.


Download and install Titanium 

You will have to sign in first and download the titanium appcelerator setup zip file. Unzip it any where. Go in to that directory and execute as any user AppeceratorStudio file. This same user should have the ownership of .npm and .appcelerator directories.
When you execute this file for the first time it just connects to appcelerator aws servers and downloads the configuration. We just cant see it . No indication what so ever. No indication in ps aux, top or netstat. So just brave your self untii this is over. This takes a looooooooooooooong time. So dont uninterrupt this. If all goes well, you have titanium.

If uninterrupted ->
You will have to simply to do the configration again. Luckily when you are  using Titanium CLI also you can do the configuration.
// This downloads titanium CLI and configure it
sudo npm install appcelerator -g
appc setup  

After this you can run AppeceratorStudio file and start working on Titanium.

Hope this help. :)
Share:

Build with Gradle

Recently one of my friends asked me to explain what a build tool is and what is Gradle. So I thought of explaining it here and go much as further as I can go smoothly and neatly.

What is a software build ?

You write code for an application. Those are the source codes. Lets say its an android application and your write Java code. When you have done writing the code you will have to make a .apk file if you want to run it on an android device. The process of converting source code -> something deployable is called building. So building may include
  • Compiling process
  • Linking related files 
  • If your software depends on external .jars, programs or whateve, solve those dependecies
  • Package your software in a deployable manner (in this case to an .apk file) 
Build tools are the tools that can do those things.
Some good tools are
C -- make
Java -- Ant,Maven,Gradle
.net --NAnt

Do we need tools for building ?

If you are doing indpendant small scale coding, you dont any FANCY build tools. But when you have large scale developement to handle with lot of different people coding on different parts and you should have like different versions of builds for different reasons and they depend on diff third party plugins, software, files your life can be like living in hell if you dont have a build tool with you. But this not the case with interpreted programs coz interpreters dont involve a compiling process hence the interpreters ;).

What is Gradle ?

Gradle is a also a built autoamtion tool. Meaning you can automatically build your project into several builds and at the same time you can automate some tests also. So gradle is opensource and used at enterprise level which is more cool. I think it came to enterprise level just because it is opensource. Power of often source huh :D. Gradle has lot of good features of ant and Maven. Now you can build Java,C,C++ apps with gradle.

Gradle is built with a Groovy a good OO Java like scripting language. So all the gradle tasks are in Groovy and if you wanna do stuff with Gradle, you ll have to learn Groovy a lil bit. Its not that actually hard. Gradle came to popularity with the start of Android Studio. I remember when I worked with Android Studio and Gradle for the first time in 2 years back , Gradle was a crappy part of the studio with that greenish slimy logo and build scripts. But as it turns out, gradle has become a indipensable tool for me now. ;) Never judge a book by its cover, huh :D

So if you wanna start with gradle, you should have it in your system. Get with package managers or download binaries or install with ecplise. There are so much you can do with gradle but we will see most common reoccurring ones like jar configs, dependency management and configs.


gradle tasks

This can show you what you can do with gradle and are as follows.
Build tasks 
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles classes 'main'.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
testClasses - Assembles classes 'test'.

Build Setup tasks
init - Initializes a new Gradle build. [incubating]
wrapper - Generates Gradle wrapper files. [incubating]

Documentation tasks
javadoc - Generates Javadoc API documentation for the main source code.

Help tasks
components - Displays the components produced by root project 'GradeDemo'. [incubating]
dependencies - Displays all dependencies declared in root project 'GradeDemo'.
dependencyInsight - Displays the insight into a specific dependency in root project 'GradeDemo'.
help - Displays a help message.
model - Displays the configuration model of root project 'GradeDemo'. [incubating]
projects - Displays the sub-projects of root project 'GradeDemo'.
properties - Displays the properties of root project 'GradeDemo'.
tasks - Displays the tasks runnable from root project 'GradeDemo'.

Verification tasks
check - Runs all checks.
test - Runs the unit tests.

Rules
Pattern: clean<TaskName>: Cleans the output files of a task.
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.
Pattern: upload<ConfigurationName>: Assembles and uploads the artifacts belonging to a configuration.


apply plugin: "java" 

This will tell the gradle system that this is a Java project. So when build is done
source files will be in -> src/main
testing source files -> src/test
all your builds -> builds/lib


repositories{mavenCentral()}
dependencies {
compile  'org.glassfish.jersey.core:jersey-client:2.22.1'
runtime 'orf.groovy:groovy:2.2'
}
Gradle can reslove dependecy problems just like in Maven and pom.xml does. So when a dependency is declared it just downloads the dependecies when the build happens from a repo mentioned. Luckily we have a in built Maven repo comes with gradle ie: mavenCentral which has lot of dependencies. Or you can use Ivy whihc is like maven repo or custom define repos.
You can also specify the type of the dependency a compile time or run time. It should be in the format of Group id : artifact id: version number (ex: 'org.glassfish.jersey.core:jersey-client:2.22.1)

sourceCompatibility = 1.8
version = '2.5'
jar {
  manifest { 
    attributes "Main-Class": 'com.kapal.gradle.Main',
"Implementation-title":"Build with gradle"
"Implementation version": version
  }

We can  add attributes to Manifest.mf which is an information file which comes with built jar. You can add any attribute to the file.

configurations {
  
 customCompile
 customCompile.transitive = false
 compile.extendsFrom(customCompile)
 compile.transitive = false
 testCompile.transitive = false
    
}

You can add configure your build(s) add custom configs for build(s) and hanldle how your build happens and how your testing builds happen.

This is what you get when a succussfull build happens













Share: