Showing posts with label JVM. Show all posts
Showing posts with label JVM. Show all posts

Monday, October 2, 2017

Java Garbage Collection, Finalize() and Memory Leaks


Can there be memory leaks in Java?

As a Java-lover, I can say this is the "Million Dollar Question"...

The answer is that it depends on what kind of memory leak you are talking about.
Classic C / C++ memory leaks occur when an application neglects to free or dispose an object when they are done with it, and it leaks. Cyclic references are a sub-case of this where the application has difficulty knowing when to free / dispose, and neglects to do it as a result. Related problems are where the application uses an object after it has been freed, or attempts to free it twice. (You could call the latter problems memory leaks, or just bugs. Either way ... )
Java and other (fully1) managed languages mostly don't suffer from these problems because the GC takes care of freeing objects that are no longer reachable. (Certainly, dangling pointer and double-free problems don't exist, and cycles are not problematic as the are for C / C++ "smart pointers".)
But in some cases GC in Java will miss objects that (from the perspective of the programmer) should be garbage collected. This happens when the GC cannot figure out that an object cannot be reached:
  • The logic / state of the program might be such that the execution paths that would use some variable cannot occur. The developer can see this as obvious, but the GC cannot be sure, and errs on the side of caution (as it is required to).
  • The programmer could be wrong about it, and the GC is avoiding what might otherwise result in a dangling reference.
Well, considering that java uses a garbage collector to collect unused objects, you can't have a dangling pointer. However, you could keep an object in scope for longer than it needs to be, which could be considered a memory leak....


Now let's, be more practical and perform a real test to see how the Java Garbage Collection works.

As we know (hope you do), the Finalize() is invoked right before an object is garbage collected, so, to demonstrate how this works we might need to create objects and wait for them to be 'garbage collected'.


On your favorite IDE, copy / paste the next code snippet: 



package com.rolandoFebreroo.GarbageCollection;

public class GarbageCollection {
    public static void main(String args[]) {
        for (int i = 0; i < 10; i ++) {
            new MyObject();
        }
    }
}
class MyObject {
 MyObject() {
        super();
        System.out.println("Object reference is located on the heap at: " + this);
    }
    protected void finalize() { 
        System.out.println("!!!You have been Finalized, baby...!!! " + this );
    }
}


As we can see, there is a simple for loop used to create 10 MyObject objects. The output is:



Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@15db9742
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@6d06d69c
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@7852e922
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@4e25154f
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@70dea4e
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@5c647e05
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@33909752
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@55f96302
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@3d4eac69
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@42a57993


Still we are not able to see how the Garbage Collector works, and if we run the same code again, we are going to get the exact same memory address for the newly created objects.
How come we didn't see the the finalize() method execute? Finalize() is not called when an object is no longer in scope, finalize is called just prior to garbage collection. Because of this, your program should utilize other methods of executing statements that need to be run before the object is destroyed. Things like closing file handles, freeing up resources, etc., should not depend on finalize() for normal program execution.

We have no way of knowing when the garbage collector is going to run. In this case, the garbage collector ran sometime after the completion of my main method, so the string literal "!!!!You have been Finalized, baby...!!!" could not be displayed to the console.

In order to demonstrate the finalize() method, I will make an infinite loop that creates an object on every iteration. Hopefully, we will see some "!!!You have been Finalized, baby...!!! " roll across the console.


For this purpose, just modify the for loop and increment the value from 'i<10' to 'i<100000'

for (int i = 0; i < 100000; i ++)



Now, Let's run the code again, but this time you should get an output similar to this:



!!!You have been Finalized, baby...!!! com.rolandoFebreroo.GarbageCollection.MyObject@2314cd97
!!!You have been Finalized, baby...!!! com.rolandoFebreroo.GarbageCollection.MyObject@5af56240
!!!You have been Finalized, baby...!!! com.rolandoFebreroo.GarbageCollection.MyObject@2212e291
!!!You have been Finalized, baby...!!! com.rolandoFebreroo.GarbageCollection.MyObject@5d75f90e
!!!You have been Finalized, baby...!!! com.rolandoFebreroo.GarbageCollection.MyObject@31b91435
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@6ae9b2f0
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@3f1870bc
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@3993c2be
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@55b0c0a6
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@726986d2
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@e0895b3
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@29a920fe


What happened here is that when we incremented the For loop, we starting creating objects on the heap memory, and eventually the Garbage Collector would wake up and start doing its job, and that is when the Finalize() is invoked and we see it in the above output.

This was just a simple exercise to understand how Java Garbage Collection works. Just remember that since Finalize() is only called right before an object is garbage collected, and this might or might not happen during the execution of your program, you shouldn't place any code that NEEDS to be executed in the Finalize().






Programming thought of the day:
  • Wikipedia: I know everything! 
  •  Google: I have everything! 
  •  Facebook: I know everybody! 
  •  Internet: Without me you are nothing! 
  • Electricity: Keep talking bitches!


Tuesday, July 25, 2017

Java Version-wise Features History


Have you ever wondered what are the new features released in all Java versions? Well, if it not your case, it was mine =) 
These are pretty much frequently asked questions in java interviews. In this page, I listing down all JDK changes from JDK 1.x to Java SE 8, sequentially. Though I have tried to cover as much as information I can gather, though if you know something which I missed below, please let me know and I will add that information.

Java SE 9 Features

Possible Release Date : September 21, 2017. Please see the updated release info here.

Proposed features are:
  • Support for multi-gigabyte heaps
  • Better native code integration
  • Self-tuning JVM
  • Java Module System
  • Money and Currency API
  • jshell: The Java Shell
  • Automatic parallelization

Java SE 8 Features

Release Date : March 18, 2014
Code name culture dropped. Included features were:

Java SE 7 Features

Release Date : July 28, 2011
This release was called “Dolphin”. Included features were:

Java SE 6 Features

Release Date : December 11, 2006
This release was called “Mustang”. Sun dropped the “.0” from the version number and version became Java SE 6. Included features were:
  • Scripting Language Support
  • Performance improvements
  • JAX-WS
  • JDBC 4.0
  • Java Compiler API
  • JAXB 2.0 and StAX parser
  • Pluggable annotations
  • New GC algorithms

J2SE 5.0 Features

Release Date : September 30, 2004
This release was called “Tiger”. Most of the features, which are asked in java interviews, were added in this release.
Version was also called 5.0 rather than 1.5. Included features are listed down below:

J2SE 1.4 Features

Release Date : February 6, 2002
This release was called “Merlin”. Included features were:
  • assert keyword
  • Regular expressions
  • Exception chaining
  • Internet Protocol version 6 (IPv6) support
  • New I/O; NIO
  • Logging API
  • Image I/O API
  • Integrated XML parser and XSLT processor (JAXP)
  • Integrated security and cryptography extensions (JCE, JSSE, JAAS)
  • Java Web Start
  • Preferences API (java.util.prefs)

J2SE 1.3 Features

Release Date : May 8, 2000
This release was called “Kestrel”. Included features were:
  • HotSpot JVM
  • Java Naming and Directory Interface (JNDI)
  • Java Platform Debugger Architecture (JPDA)
  • JavaSound
  • Synthetic proxy classes

J2SE 1.2 Features

Release Date : December 8, 1998
This release was called “Playground”. This was a major release in terms of number of classes added (almost trippled the size). “J2SE” term was introduced to distinguish the code platform from J2EE and J2ME. Included features were:
  • strictfp keyword
  • Swing graphical API
  • Sun’s JVM was equipped with a JIT compiler for the first time
  • Java plug-in
  • Collections framework

JDK 1 Features

Release Date : January 23, 1996
This was the initial release and was originally called Oak. This had very unstable APIs and one java web browser named WebRunner.
The first stable version, JDK 1.0.2, was called Java 1.
On February 19, 1997, JDK 1.1 was released havind a list of big features such as:
  • AWT event model
  • Inner classes
  • JavaBeans
  • JDBC
  • RMI
  • Reflection which supported Introspection only, no modification at runtime was possible.
  • JIT (Just In Time) compiler for Windows
Again, feel free to suggest any java feature in any java version which I missed in above lists.
Happy Learning !!







Programming thought of the day:
  • 1f u c4n r34d th1s u r34lly n33d t0 g37 l41d.


Friday, March 31, 2017

Microservice Architecture - Explanation, pros and cons


As most Software Developers out there, most of my experience is with (huge) monolithic apps. So when I first read or heard about microservices I was a little confused about how they work and how to implement this kind of architecture, and most important.. does it work? any pros and cons? is it the next step in the development process?

I don't believe microservices can be considered "the best aproach" in every single situation. However, it looks like a good option. But, as everything in life, all is relative...

I'll show you some facts I found on the internet about microservices architecture so you can have a better understanding about it. It you are confused (as I was), hope it helps to clarify some concepts....


1. What is Architecture (Software)?

Architecture is the fundamental organization of a system embodied in its components (i.e. Web Server, Application Server, Databases,Storage, Communication layer, etc…), their relationships to each other, and to the environment (i.e. deployment environment shared server, dedicated server, cloud deployment, etc..), and the principles guiding its design and evolution.

2. What is microservice architecture ?

Microservice means developing a single, small, meaningful functional feature as single service, each service has it’s own process and communicate with lightweight mechanism, deployed in single or multiple servers.

3. Advantages of microservice architecture ?

Each micro service is small and focused on a specific feature / business requirement.
Microservice can be developed independently by small team of developers (normally 2 to 5 developers).
Microservice is loosely coupled, means services are independent, in terms of development and deployment both.
Microservice can be developed using different programming language (Personally I don’t suggest to do it).
Microservice allows easy and flexible way to integrate automatic deployment with Continuous Integration tools (for e.g: Jenkins, Hudson, bamboo etc..).
The productivity of a new team member will be quick enough.
Microservice is easy to understand, modify and maintain for a developer because separation of code,small team and focused work.
Microservice allows you to take advantage of emerging and latest technologies (framework, programming language , programming practice, etc.).
Microservice has code for business logic only, No mixup with HTML,CSS or other UI component.
Microservice is easy to scale based on demand.
Microservice can deploy on commodity hardware or low / medium configuration servers.
Easy to integrate 3rd party service.
Every microservice has it’s own storage capability but it depends on the project’s requirement, you can have common database like MySQL or Oracle for all services.

4. Disadvantages of microservice architecture ?

Microservice architecture brings a lot of operations overhead.
DevOps Skill required (http://en.wikipedia.org/wiki/DevOps).
Duplication of Effort.
Distributed System is complicated to manage .
Default to trace problem because of distributed deployment.
Complicated to manage whole products when number of services increases.

5. In which case / requirement microservice architecture best fit ?

When you need to support Desktop, web , mobile, Smart TVs, Wearable, etc… or you don’t know in future which kind of devices you need to support.

6. Which products / companies are using Microservie architecture?

Most large scale web sites including Twitter, Netflix, Amazon and eBay have evolved from a monolithic architecture to a microservices architecture.

7. How independent micro services communicate with each other?

It’s depend upon requirement, normally developers use HTTP/REST with JSON or Protobuf (Binary protocol) but are free to use any communication protocol.

8. Why is it that everyone are talking about microservices now?

It’s been nearly 15 years since the concept of Service Oriented Architecture really took hold. With the improvement of RESTful web service and JSON as a data interchange format has made it easier than ever to build easily interconnectable services simply and quickly.

9. Presentation

http://www.infoq.com/presentations/Micro-Services



10. Video





11. Picture: Monolithic vs Modular vs Service oriented architecture







Programming thought of the day:


  • Are you an exception? I bet I can catch you. =)