Comparing Wrappers other than String

public class A {
public static void main(String[] args) {
Integer i1=100; Integer i2=100;
System.out.println(i1==i2);//true
Integer i3=200; Integer i4=200;
System.out.println(i3==i4);//false -- why ??
}
}

Reason:

The Integer wrapper class interns the objects from -127 to +128. So all Integers with a value less than 128 are the same as they are interned. The values greater than 128 are not the same because they are not interned.

The JVM will create a cache of objects(something similar to the string constant pool) for the above range and assigns the same object(if it already exists) when ever a new object with the same value is created. So in your case, the two Integers for 100 will use the same object and the ones for 200 won’t be the same.

you assign a integral literal to a Integer reference, it will invoke the Integer.valueOf(..) method.

This method uses the famous Fly-weigh pattern. That is that the -128~127 integers are cached. So the “i1==i2” will be true. Of course, you can change the cache range by setting IntegerCache.low or IntegerCache.high which are static variables.

Always compare wrapper classes with equals(e).

Writing thread safe static methods

Recently, I was writing a static method and a thought of concurrency crossed my mind. So, I read and discussed about this with a colleague and I am sharing my understandings.

Memory in java is split up into two kinds – the heap and the stacks. The heap is where all the objects live and the stacks are where the threads do their work. Each thread has its own stack and can’t access each others stacks.

Each thread also has a pointer into the code which points to the bit of code they’re currently running. When a thread starts running a new method it saves the arguments and local variables in that method on its own stack. 
Some of these values might be pointers to objects on the heap. 

If two threads are running the same method at the same time they will both have their code pointers pointing at that method and have their own copies of arguments and local variables on their stacks.
They will only interfere with each other if the things on their stacks point to the same objects on the heap.
In which case all sorts of things might happen. But For example Strings are immutable (cannot be changed) so we’re safe if this is the only object being “shared”.

In Summary, While writing static methods try to keep the scope of variables to the smallest possible. this way most probably we are thread safe.
If shared objects are immutable then also we are good to go.

Garbage Collection in JAVA

1) objects are created on heap in Java irrespective of there scope e.g. local or member variable. while its worth noting that class variables or static members are created in method area of Java memory space and both heap and method area is shared between different thread.
2) Garbage collection is a mechanism provided by Java Virtual Machine to reclaim heap space from objects which are eligible for Garbage collection.
3) Garbage collection relieves java programmer from memory management which is essential part of C++ programming and gives more time to focus on business logic.
4) Garbage Collection in Java is carried by a daemon thread called Garbage Collector.
5) Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
6) You as Java programmer can not force Garbage collection in Java; it will only trigger if JVM thinks it needs a garbage collection based on Java heap size.
7) There are methods like System.gc () and Runtime.gc () which is used to send request of Garbage collection to JVM but it’s not guaranteed that garbage collection will happen.
8) If there is no memory space for creating new object in Heap Java Virtual Machine throws OutOfMemoryError or java.lang.OutOfMemoryError heap space.

When an Object becomes Eligible for Garbage Collection

An Object becomes eligible for Garbage collection if its not reachable from any live threads or any static references in other words you can say that an object becomes eligible for garbage collection if its all references are null.

Cyclic dependencies are not counted as reference so if Object A has reference of object B and object B has reference of Object A and they don’t have any other live reference then both Objects A and B will be eligible for Garbage collection.

Generally an object becomes eligible for garbage collection in Java on following cases:
1) All references of that object explicitly set to null e.g. object = null
2) Object is created inside a block and reference goes out scope once control exit that block.
3) Parent object set to null, if an object holds reference of another object and when you set container object’s reference null, child or contained object automatically becomes eligible for garbage collection.

Memory Leaks in JAVA

When we write programs, memory management is the bottleneck issue on performance.

JAVA handles memory management through Garbage Collection. You were promised that Garbage Collection (GC) in Java will relieve you from the mundane duties of allocating, tracking, and freeing the heap memory. Indeed, the promise has been delivered, Yes Its true.Garbage collection is one of the powerful features of  JAVA. so it is reasonable — and to quite an extent correct — for you to conclude that there will be no memory leaks in your Java program. However, the catch is that GC can take care of only typical heap management problems.

We often hear programmers saying that JVM takes care of Garbage collection and programmers don’t need to worry on them. But, there are situations where memory leaks can still occur.

Common memory leak causes in Java

 Java may not have pointers. but memory leaks still happen. You can easily consume most of your memory on the heap if you’re not taking care to free up memory you no longer need. The possibility for memory leaks seems to go up dramatically the more programmers work on a single project. This is especially true if some don’t fully understand the java memory model.

In this post I’m going to point the most common scenarios likely to cause a memory leak.Common causes of memory leaks in Java

1) Static variables

Many junior programmers in java do not fully understand what static means. This misunderstanding is perhaps the most common cause of unintended memory leaks. To understand static variables, think of the scope of a variable, or, where does a variable live? If you declare a variable inside a  method, this is called a method scoped variable. It only exists while that method is running and is usually destroyed and released for garbage collection as soon as the method exits. If you declare a variable inside a class definition, then it is OBJECT scoped. It is NOT CLASS SCOPED. Remember a class is a blueprint for an object, and an instance of an object is completely different then the class from which it was built. The variable that is object scoped will be deferenced and ready for garbage collection as soon as all references to the object are destroyed. When you null out the only reference to an object, it is properly deferenced.

STATIC VARIABLE is CLASS SCOPED. A static variable lives on the blueprint of an object, not the object itself. The classes in java are usually loaded right away at startup and are never deferenced until you shut down the JVM. If you declare a variable as static it will live for the entire lifetime of the JVM, unless it is individually nulled out. If a static variable references non static objects, it effectively makes those objects static as well. You can clear out a static collection, but depending on how the collection is cleared you may or may not be freeing up memory. Be careful. If you don’t understand why something needs to be static, ask someone who does understand. Static is a surprisingly sticky subject and many career programmers still don’t fully understand what it means.

2) Poorly implemented data structures

Poorly implemented data structures can be just as damaging and confusing as either of the other two common issues.  When you store data in a common array, you have to null out the indices of the array if you want the objects contained within to be deferenced. A seemingly simple thing like that can become easily obfuscated and forgotten when implementing a complicated data structure, like a specialized tree or specialized hash table.

The best thing to do in most scenarios is try to encourage the use of standard data structures (usually through sun or apache) that have been used by many people, thoroughly tested, and de-bugged.

You will sometimes run into career developers who have spent too much time implementing their own vector class or their own tree structures to ever consider using the standard tools. In fact, many of these ‘blinded by undeserved ego’ types will not even know of the common classes developed a decade ago. If you find yourself debugging memory leaks in your co-workers data structures to often, consider looking for a different development group to be apart of, or a different company. It’s good to have a grounded understanding of how all the major data structures work, it’s bad to assume that everything you do will somehow be magically better than other (almost always smarter) professionals.


Why are you a programmer ?

Being a Software Developer, you should know why are you a programmer?

Are you in Programming just because you have e done MCA or BE in Computers ?. Answer of majority people is Yes. But it should not be the case.

One of the major problems with the people is that many just aren’t interested in programming.

I have seen profiles of people who are not even computer graduates and they are programmers.

From my perspective, Creating computer programs is not only a job.

Majority of the people aspiring to be programmers won’t write a program until they are FORCED to by their college or by their employer. And that is NOT good.

I would say 70% of the people opting for this profession are doing it just because They thinks that it has good money and a very convenient way of getting abroad.

And when people do something without having a real liking or passion for that thing, it shows up in the quality of the output.

You can teach people syntax of JAVA and SQL and any other programming language. But you can’t really teach people to think creatively. Think of a solution for a problem. And certainly you cant teach someone to love their profession.

Well, One thing is also that I am not talking about individuals situation but this is the true fact which can’t be ignored.