Wednesday, April 30, 2014

Finding the JAR files which contain a specific .class file on Linux machine

This program searches through all .jar files in the current directory, and in any sub-directories, looking for the class that you specify. This can be very handy if you need to use a class in a Java program, but aren't sure which .jar file contains it.

Logic of script: The key is to get a list of all the jar files in present directory, open each jar archive and search it with our input classname, and for all positive output, print the name of the jar file on screen.

Thursday, April 24, 2014

Synchronization in Java : class and object locking concept

People talk about two types of multi-threaded locking - object and class. In my knowledge, locking is done on objects only. Let me explain.

Case 1: On objects we create using new or factory methods etc.
void synchronized myMethod(Type param) {
  //will lock on the instance used to call this method
synchronized(this) {
 //will lock on current object
synchronized(obj1) {
 //will lock on specified obj1 object

Monday, April 21, 2014

Writing singleton classes in Java

Singleton classes are those classes which can be instantiated only once. We need to restrict the creation of multiple instances of that class by blocking constructor access using new keyword etc, and instead regulate the incoming instance requests by creating the instance only once and return the same instance time and again on multiple calls.
Where do we actually need this singleton design pattern?

Friday, April 11, 2014

Bubble Sorting in Java

Bubble sorting sorts the array in-place bubbling up the largest value.
Worst case - O(n^2); average case - O(n^2); best case - O(n)

Visualization: (src. Wiki)