Pages

Sunday, May 06, 2012

Singleton Design Pattern

Singleton Pattern:

Intent

 - Ensure that only one instance of a class is created.
 - Provide a global point of access to the object.

Implementation

The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.

Singleton Pattern

Motivation

Sometimes it's important to have only one instance for a class. For example, in a system there should be only one window manager (or only a file system or only a print spooler). Usually singletons are used for centralized management of internal or external resources and they provide a global point of access to themselves.

The singleton pattern is one of the simplest design patterns: it involves only one class which is responsible to instantiate itself, to make sure it creates not more than one instance; in the same time it provides a global point of access to that instance. In this case the same instance can be used from everywhere, being impossible to invoke directly the constructor each time.

Intent

 - Ensure that only one instance of a class is created.
 - Provide a global point of access to the object.

Implementation

The implementation involves a static member in the "Singleton" class, a private constructor and a static public method that returns a reference to the static member.

The Singleton Pattern defines a getInstance operation which exposes the unique instance which is accessed by the clients. getInstance() is is responsible for creating its class unique instance in case it is not created yet and to return that instance.

class Singleton
{
    private static Singleton instance;
    private Singleton()
    {
        ...
    }
    public static synchronized Singleton getInstance()
    {
        if (instance == null)
            instance = new Singleton();
        return instance;
    }
    ...
    public void doSomething()
    {
        ...   
    }
}

You can notice in the above code that getInstance method ensures that only one instance of the class is created. The constructor should not be accessible from the outside of the class to ensure the only way of instantiating the class would be only through the getInstance method.

The getInstance method is used also to provide a global point of access to the object and it can be used in the following manner: Singleton.getInstance().doSomething(); 

Applicability & Examples

According to the definition the singleton pattern should be used when there must be exactly one instance of a class, and when it must be accessible to clients from a global access point. Here are some real situations where the singleton is used:

Example 1 - Logger Classes

The Singleton pattern is used in the design of logger classes. This classes are usually implemented as a singletons, and provides a global logging access point in all the application components without being necessary to create an object each time a logging operations is performed.

Example 2 - Configuration Classes

The Singleton pattern is used to design the classes which provides the configuration settings for an application. By implementing configuration classes as Singleton not only that we provide a global access point, but we also keep the instance we use as a cache object. When the class is instantiated( or when a value is read ) the singleton will keep the values in its internal structure. If the values are read from the database or from files this avoids the reloading the values each time the configuration parameters are used.

Example 3 - Accessing resources in shared mode

It can be used in the design of an application that needs to work with the serial port. Let's say that there are many classes in the application, working in an multi-threading environment, which needs to operate actions on the serial port. In this case a singleton with synchronized methods could be used to be used to manage all the operations on the serial port.

Example 4 - Factories implemented as Singletons

Let's assume that we design an application with a factory to generate new objects(Account, Customer, Site, Address objects) with their ids, in an multi-threading environment. If the factory is instantiated twice in 2 different threads then is possible to have 2 overlapping ids for 2 different objects. If we implement the Factory as a singleton we avoid this problem. Combining Abstract Factory or Factory Method and Singleton design patterns is a common practice.

Specific problems and implementation

Thread-safe implementation for multi-threading use.

A robust singleton implementation should work in any conditions. This is why we need to ensure it works when multiple threads uses it. As seen in the previous examples singletons can be used specifically in multi-threaded application to make sure the reads/writes are synchronized.

Lazy instantiation using double locking mechanism.

The standard implementation shown in the above code is a thread safe implementation, but it's not the best thread-safe implementation because synchronization is very expensive when we are talking about the performance. We can see that the synchronized method getInstance does not need to be checked for synchronization after the object is initialized. If we see that the singleton object is already created we just have to return it without using any synchronized block. This optimization consist in checking in an unsynchronized block if the object is null and if not to check again and create it in an synchronized block. This is called double locking mechanism.

In this case case the singleton instance is created when the getInstance() method is called for the first time. This is called lazy instantiation and it ensures that the singleton instance is created only when it is needed.

//Lazy instantiation using double locking mechanism.
class Singleton
{
    private static Singleton instance;
    private Singleton()
    {
    System.out.println("Singleton(): Initializing Instance");
    }
    public static Singleton getInstance()
    {
        if (instance == null)
        {
            synchronized(Singleton.class)
            {
            if (instance == null)
                {
                    System.out.println("getInstance(): First time getInstance was invoked!");
                    instance = new Singleton();
                }
            }           
        }
        return instance;
    }
    public void doSomething()
    {
        System.out.println("doSomething(): Singleton does something!");
    }
}

Early instantiation using implementation with static field 

In the following implementation the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the instance member is declared static. This is why in we don't need to synchronize any portion of the code in this case. The class is loaded once this guarantee the uniquity of the object.

Singleton - A simple example (java)

//Early instantiation using implementation with static field.
class Singleton
{
    private static Singleton instance = new Singleton();
    private Singleton()
    {
        System.out.println("Singleton(): Initializing Instance");
    }
    public static Singleton getInstance()
    {   
        return instance;
    }
    public void doSomething()
    {
        System.out.println("doSomething(): Singleton does something!");
    }


Protected constructor

It is possible to use a protected constructor to in order to permit the subclassing of the singeton. This technique has 2 drawbacks that makes singleton inheritance impractical:

 - First of all, if the constructor is protected, it means that the class can be instantiated by calling the constructor from another class in the same package. A possible solution to avoid it is to create a separate package for the singleton.
 - Second of all, in order to use the derived class all the getInstance calls should be changed in the existing code from  Singleton.getInstance() to NewSingleton.getInstance().

Multiple singleton instances if classes loaded by different class loaders access a singleton.

If a class(same name, same package) is loaded by 2 different class loaders they represents 2 different classes in memory.

Serialization

If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized and then deserialized more than once, there will be multiple instances of Singleton created. In order to avoid this the readResolve method should be implemented. See Serializable () and readResolve Method () in javadocs.

public class Singleton implements Serializable {
    ...
    // This method is called immediately after an object of this class is deserialized.
    // This method returns the singleton instance.
    protected Object readResolve() {
        return getInstance();
    }
}  

Abstract Factory and Factory Methods implemented as singletons.

There are certain situations when the a factory should be unique. Having 2 factories might have undesired effects when objects are created. To ensure that a factory is unique it should be implemented as a singleton. By doing so we also avoid to instantiate the class before using it.

Hot Spot:

- Multi-threading - A special care should be taken when singleton has to be used in a multi-threading application.
- Serialization - When Singletons are implementing Serializable interface they have to implement  readResolve() method in order to avoid having 2 different objects.
- Classloaders -  If the Singleton class is loaded by 2 different class loaders we'll have 2 different classes, one for each class loader.
- Global Access Point represented by the class name - The singleton instance is obtained using the class name. At the first view this is an easy way to access it, but it is not very flexible. If we need to replace the Sigleton class, all the references in the code should be changed accordingly.

Saturday, May 05, 2012

Intialization Precedance in Java with Constructors, Intialization block, Static block

Say a project contains several classes, each of which has a static initializer block. In what order do those blocks run? I know that within a class, such blocks are run in the order they appear in the code. I've read that it's the same across classes, but some sample code I wrote disagrees with that. I used this code:

package pkg;
public class LoadTest {
   
public static void main(String[] args) {
       
System.out.println("START");
       
new Child();
       
System.out.println("END");
   
}
}
class Parent extends Grandparent {
   
// Instance init block
   
{
       
System.out.println("instance - parent");
   
}

   
// Constructor
   
public Parent() {
       
System.out.println("constructor - parent");
   
}

   
// Static init block
   
static {
       
System.out.println("static - parent");
   
}
}
class Grandparent {
   
// Static init block
   
static {
       
System.out.println("static - grandparent");
   
}

   
// Instance init block
   
{
       
System.out.println("instance - grandparent");
   
}

   
// Constructor
   
public Grandparent() {
       
System.out.println("constructor - grandparent");
   
}
}
class Child extends Parent {
   
// Constructor
   
public Child() {
       
System.out.println("constructor - child");
   
}

   
// Static init block
   
static {
       
System.out.println("static - child");
   
}

   
// Instance init block
   
{
       
System.out.println("instance - child");
   
}
}

The obvious answer from that is that parents' blocks run before their children's, but that could just be a coincidence and doesn't help if two classes aren't in the same hierarchy.

Output:

START
static - grandparent
static - parent
static - child
instance - grandparent
constructor - grandparent
instance - parent
constructor - parent
instance - child
constructor - child
END


What is difference between Strings and String Literals

What is a String Literal? A String literal is a sequence of characters between quotation marks, such as "string" or "literal". You've probably used String literals hundreds of times in your own applications. You might not, however, have realized just how special String literals are in Java.

Strings are Immutable

So what makes String literals so special? Well, first of all, it's very important to remember that String objects are immutable. That means, once created, a String object cannot be changed (short of using something like reflection to get at private data). Immutable, you say? Unchangeable? What about this code?

Source Code
            
public class ImmutableStrings
{
    public static void main(String[] args)
    {
        String start = "Hello";
        String end = start.concat(" World!");
        System.out.println(end);
    }
}

// Output

Hello World!
            

Well look at that, the String changed...or did it? In that code, no String object was ever changed. We start by assigning "Hello" to our variable, start. That causes a new String object to be created on the heap and a reference to that object is stored in start. Next, we invoke the method concat(String) on that object. Well, here's the trick, if we look at the API Spec for String, you'll see this in the description of the concat(String) method:

Concatenates the specified string to the end of this string.
If the length of the argument string is 0, then this String object is returned. Otherwise, a new String object is created, representing a character sequence that is the concatenation of the character sequence represented by this String object and the character sequence represented by the argument string.


Examples:


    "cares".concat("s") returns "caress"
    "to".concat("get").concat("her") returns "together"


Parameters:
    str - the String that is concatenated to the end of this String.
Returns:
    a string that represents the concatenation of this object's characters followed by the string argument's characters.
Notice the part I've highlighted in bold. When you concatenate one String to another, it doesn't actually change the String object, it simply creates a new one that contains the contents of both of the original Strings, one after the other. That's exactly what we did above. The String object referenced by the local variable start never changed. In fact, if you added the statement System.out.println(start); after you invoked the concat method, you would see that start still referenced a String object that contained just "Hello". And just in case you were wondering, the '+' operator does the exact same thing as the concat() method.


Strings really are immutable.

Storage of Strings - The String Literal Pool

If you've done any preparation for the SCJP exam (and quite possibly even if you haven't), you've probably heard of the "String Literal Pool." What is the String Literal Pool? Most often, I hear people say that it is a collection of String objects. Although that's close, it's not exactly correct. Really, it's a collection of references to String objects. Strings, even though they are immutable, are still objects like any other in Java. Objects are created on the heap and Strings are no exception. So, Strings that are part of the "String Literal Pool" still live on the heap, but they have references to them from the String Literal Pool.

Yeah, so that doesn't really explain what the pool is, or what it's for, does it? Well, because String objects are immutable, it's safe for multiple references to "share" the same String object. Take a look at this example:

Source Code
            
public class ImmutableStrings
{
    public static void main(String[] args)
    {
        String one = "someString";
        String two = "someString";
        
        System.out.println(one.equals(two));
        System.out.println(one == two);
    }
}

// Output

true
true
            

In such a case, there is really no need to make two instances of an identical String object. If a String object could be changed, as a StringBuffer can be changed, we would be forced to create two separate objects. But, as we know that String objects cannot change, we can safely share a String object among the two String references, one and two. This is done through the String literal pool. Here's how it is accomplished:

When a .java file is compiled into a .class file, any String literals are noted in a special way, just as all constants are. When a class is loaded (note that loading happens prior to initialization), the JVM goes through the code for the class and looks for String literals. When it finds one, it checks to see if an equivalent String is already referenced from the heap. If not, it creates a String instance on the heap and stores a reference to that object in the constant table. Once a reference is made to that String object, any references to that String literal throughout your program are simply replaced with the reference to the object referenced from the String Literal Pool.

So, in the example shown above, there would be only one entry in the String Literal Pool, which would refer to a String object that contained the word "someString". Both of the local variables, one and two, would be assigned a reference to that single String object. You can see that this is true by looking at the output of the above program. While the equals() method checks to see if the String objects contain the same data ("someString"), the == operator, when used on objects, checks for referential equality - that means it will return true if and only if the two reference variables refer to the exact same object. In such a case, the references are equal. From the above output, you can see that the local variables, one and two, not only refer to Strings that contain the same data, they refer to the same object.

Graphically, our objects and references would look something like this:




Note, however, that this is a special behavior for String Literals. Constructing Strings using the "new" keyword implies a different sort of behavior. Let's look at an example:

Source Code
            
public class ImmutableStrings
{
    public static void main(String[] args)
    {
        String one = "someString";
        String two = new String("someString");
        
        System.out.println(one.equals(two));
        System.out.println(one == two);
    }
}

// Output

true
false
            

In this case, we actually end up with a slightly different behavior because of the keyword "new." In such a case, references to the two String literals are still put into the constant table (the String Literal Pool), but, when you come to the keyword "new," the JVM is obliged to create a new String object at run-time, rather than using the one from the constant table.

In such a case, although the two String references refer to String objects that contain the same data, "someString", they do not refer to the same object. That can be seen from the output of the program. While the equals() method returns true, the == operator, which checks for referential equality, returns false, indicating that the two variables refer to distinct String objects.

Once again, if you'd like to see this graphically, it would look something like this. Note that the String object referenced from the String Literal Pool is created when the class is loaded while the other String object is created at runtime, when the "new String..." line is executed.




If you'd like to get both of these local variables to refer to the same object, you can use the intern() method defined in String. Invoking two.intern() will look for a String object referenced from the String Literal Pool that has the same value as the one you invoked the intern method upon. If one is found, a reference to that String is returned and can be assigned to your local variable. If you did so, you'd have a picture that looks just like the one above, with both local variables, one and two, referring to the same String object, which is also referenced from the String Literal Pool. At that point, the second String object, which was created at run-time, would be eligible for garbage collection.

Garbage Collection

What makes an object eligible for garbage collection? If you're preparing for the SCJP exam (or even if you're not), the answer to that question should roll right off your tongue. An object is eligible for garbage collection when it is no longer referenced from an active part of the application. Anyone see what is special about garbage collection for String literals? Let's look at an example and see if you can see where this is going.

Source Code
            
public class ImmutableStrings
{
    public static void main(String[] args)
    {
        String one = "someString";
        String two = new String("someString");
        
        one = two = null;
    }
}
            

Just before the main method ends, how many objects are available for garbage collection? 0? 1? 2?

The answer is 1. Unlike most objects, String literals always have a reference to them from the String Literal Pool. That means they always have a reference to them and are, therefore, not eligible for garbage collection. This is the same example as I used above so you can see what our picture looked liked originally there. Once we assign our variables, one and two, to null, we end up with a picture that looks like this:




As you can see, even though neither of our local variables, one or two, refer to our String object, there is still a reference to it from the String Literal Pool. Therefore, the object is not eligible for garbage collection. The object is always reachable through use of the intern() method, as referred to earlier.

Conclusion

Like I said at the outset of this article, virtually none of this information is included on the SCJP exam. However, I constantly see this question coming up in the SCJP forum and on various mock exams. These are a few of the highlights you can keep in mind when it comes to String literals:
  • Equivalent String Literals (even those stored in separate classes in separate packages) will refer to the same String object.
  • In general, String Literals are not eligible for garbage collection. Ever.
  • Strings created at run-time will always be distinct from those created from String Literals.
  • You can reuse String Literals with run-time Strings by utilizing the intern() method.
  • The best way to check for String equality is to use the equals() method.

Sunday, April 01, 2012

How to setup MySQL replication broken between Master Slave MySQL Multi-Master Configuration

1. cd ~/mysql
2. Create one config file (my_backup.cnf) for backup. Sample config files given below:

a. Your original config file contents (my.cnf):

datadir = ~/mysql/data
innodb_data_home_dir = ~/mysql/data
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = ~/mysql/data
set-variable = innodb_log_files_in_group=2
set-variable = innodb_log_file_size=20M

b. New backup config file contents (my_backup.cnf):

datadir = ~/mysql/backup
innodb_data_home_dir = ~/mysql/backup
innodb_data_file_path = ibdata1:10M:autoextend
innodb_log_group_home_dir = ~/mysql/backup
set-variable = innodb_log_files_in_group=2
set-variable = innodb_log_file_size=20M

3. Take backup using following script:

mysql]# bin/ibbackup conf/my.cnf conf/my_backup.cnf

4. Backup folder will look something like this:

$ ls -lh ~/mysql/backup
total 38M
-rw-r-----    1 sqladmin    sqladmin           12M Jan 21 18:40 ibbackup_logfile
-rw-r-----    1 sqladmin    sqladmin           14M Jan 21 18:35 ibdata1.ibz
-rw-r-----    1 sqladmin    sqladmin          8.8M Jan 21 18:37 ibdata2.ibz
-rw-r-----    1 sqladmin    sqladmin          2.2M Jan 21 18:40 ibdata3.ibz

5. Now we apply the log to get the backup stable with any changes that happened while we were taking backup.

mysql]# bin/ibbackup --apply-log conf/my_backup.cnf

InnoDB Hot Backup version 3.0.0; Copyright 2002-2005 Innobase Oy
...
ibbackup: Last MySQL binlog file position 0 11751329, file name ./mysql-bin.000030
ibbackup: The first data file is '~/mysql/backup/ibdata1'
ibbackup: and the new created log files are at '~/mysql/backup/'
081107 15:42:17  ibbackup: Full backup prepared for recovery successfully!

6. Note:

Following line is important. Save it for future reference:

"ibbackup: Last MySQL binlog file position 0 11751329, file name ./mysql-bin.000030"

7. Now copy the backup to the slave machine (preferrably, by tarring all backup files).
8. Stop the slave server, and put these backup files into the mysql/data directory
9. Please make sure they are all `chown sqladmin:sqladmin`.
10. Add the directive `skip-slave-start` into the conf/my.cnf file (to prevent mysql from being slave, keep replication stopped.
11. Save conf/my.cnf file.
12. Start mysql.
13. Connect to mysql prompt:

mysql]# bin/mysql --defaults-file=conf/my.cnf

14. Check the slave is stopped:

sqladmin@localhost [(none)]>stop slave;

15. Update the master config using:

sqladmin@localhost [(none)]>CHANGE MASTER TOMASTER_LOG_FILE='mysql-bin.000030',MASTER_LOG_POS=11751329;

The two values are the ones which you have noted down before.

16. Now start replication:

sqladmin@localhost [(none)]>start slave;

17. And check replication status:

sqladmin@localhost [(none)]>show slave status\G;


(should look like)

sqladmin@localhost [(none)]>show slave status\G;
*************************** 1. row ***************************
             Slave_IO_State: Waiting for master to send event
                Master_Host: v-cps3.persistent.co.in
                Master_User: sqladmin_repl
                Master_Port: 3306
              Connect_Retry: 60
            Master_Log_File: mysql-bin.000030
        Read_Master_Log_Pos: 12855143
             Relay_Log_File: v-cps3-relay-bin.000002
              Relay_Log_Pos: 11726383
      Relay_Master_Log_File: mysql-bin.000030
           Slave_IO_Running: Yes
          Slave_SQL_Running: Yes
            Replicate_Do_DB:
        Replicate_Ignore_DB:
         Replicate_Do_Table:
     Replicate_Ignore_Table:
    Replicate_Wild_Do_Table:
Replicate_Wild_Ignore_Table:
                 Last_Errno: 0
                 Last_Error:
               Skip_Counter: 0
        Exec_Master_Log_Pos: 12855143
            Relay_Log_Space: 11726383
            Until_Condition: None
             Until_Log_File:
              Until_Log_Pos: 0
         Master_SSL_Allowed: No
         Master_SSL_CA_File:
         Master_SSL_CA_Path:
            Master_SSL_Cert:
          Master_SSL_Cipher:
             Master_SSL_Key:
      Seconds_Behind_Master: 0

18. Finally, remove that skip-slave-start directive from the conf/my.cnf file.

robots.txt: For Indexing and Crawling of Search Engines

Although the robots.txt file is a very important file if you want to have a good ranking on search engines, many Web sites don't offer this file.
If your Web site doesn't have a robots.txt file yet, read on to learn how to create one. If you already have a robots.txt file, read our tips to make sure that it doesn't contain errors.

What is robots.txt?
When a search engine crawler comes to your site, it will look for a special file on your site. That file is called robots.txt and it tells the search engine spider, which Web pages of your site should be indexed and which Web pages should be ignored.
The robots.txt file is a simple text file (no HTML), that must be placed in your root directory, for example:
    http://www.yourwebsite.com/robots.txt

How do I create a robots.txt file?
As mentioned above, the robots.txt file is a simple text file. Open a simple text editor to create it. The content of a robots.txt file consists of so-called "records".
A record contains the information for a special search engine. Each record consists of two fields: the user agent line and one or more Disallow lines. Here's an example:
    User-agent: googlebot
    Disallow: /cgi-bin/
This robots.txt file would allow the "googlebot", which is the search engine spider of Google, to retrieve every page from your site except for files from the "cgi-bin" directory. All files in the "cgi-bin" directory will be
ignored by googlebot.
The Disallow command works like a wildcard. If you enter
    User-agent: googlebot
    Disallow: /support
both "/support-desk/index.html" and "/support/index.html" as well as all other files in the "support" directory would not be indexed by search engines.
If you leave the Disallow line blank, you're telling the search engine that all files may be indexed. In any case, you must enter a Disallow line for every User-agent record.
If you want to give all search engine spiders the same rights, use the following robots.txt content:
    User-agent: *
    Disallow: /cgi-bin/

Where can I find user agent names?
You can find user agent names in your log files by checking for requests to robots.txt. Most often, all search engine spiders should be given the same rights. in that case, use "User-agent: *" as mentioned above.

Things you should avoid
If you don't format your robots.txt file properly, some or all files of your Web site might not get indexed by search engines. To avoid this, do the following:
  1. Don't use comments in the robots.txt file

    Although comments are allowed in a robots.txt file, they might confuse some search engine spiders.

    "Disallow: support # Don't index the support directory" might be misinterepreted as "Disallow: support#Don't index the support directory".


  2. Don't use white space at the beginning of a line. For example, don't write

    placeholder User-agent: *
    place Disallow: /support

    but

    User-agent: *
    Disallow: /support


  3. Don't change the order of the commands. If your robots.txt file should work, don't mix it up. Don't write

    Disallow: /support
    User-agent: *

    but

    User-agent: *
    Disallow: /support


  4. Don't use more than one directory in a Disallow line. Do not use the following

    User-agent: *
    Disallow: /support /cgi-bin/ /images/

    Search engine spiders cannot understand that format. The correct syntax for this is

    User-agent: *
    Disallow: /support
    Disallow: /cgi-bin/
    Disallow: /images/


  5. Be sure to use the right case. The file names on your server are case sensitve. If the name of your directory is "Support", don't write "support" in the robots.txt file.


  6. Don't list all files. If you want a search engine spider to ignore all files in a special directory, you don't have to list all files. For example:

    User-agent: *
    Disallow: /support/orders.html
    Disallow: /support/technical.html
    Disallow: /support/helpdesk.html
    Disallow: /support/index.html

    You can replace this with

    User-agent: *
    Disallow: /support


  7. There is no "Allow" command

    Don't use an "Allow" command in your robots.txt file. Only mention files and directories that you don't want to be indexed. All other files will be indexed automatically if they are linked on your site.

Tips and tricks:
1. How to allow all search engine spiders to index all files
    Use the following content for your robots.txt file if you want to allow all search engine spiders to index all files of your Web site:
    User-agent: *
    Disallow:
2. How to disallow all spiders to index any file
    If you don't want search engines to index any file of your Web site, use the following:
    User-agent: *
    Disallow: /
3. Where to find more complex examples.
    If you want to see more complex examples, of robots.txt files, view the robots.txt files of big Web sites:
Your Web site should have a proper robots.txt file if you want to have good rankings on search engines. Only if search engines know what to do with your pages, they can give you a good ranking.

JVM Garbage Collector Approaches

Two basic approaches to distinguishing live objects from garbage are reference counting and tracing. Reference counting garbage collectors distinguish live objects from garbage objects by keeping a count for each object on the heap. The count keeps track of the number of references to that object. Tracing garbage collectors actually trace out the graph of references starting with the root nodes. Objects that are encountered during the trace are marked in some way. After the trace is complete, unmarked objects are known to be unreachable and can be garbage collected.

1. Reference Counting Collectors:

Reference counting was an early garbage collection strategy. In this approach, a reference count is maintained for each object on the heap. When an object is first created and a reference to it is assigned to a variable, the object's reference count is set to one. When any other variable is assigned a reference to that object, the object's count is incremented. When a reference to an object goes out of scope or is assigned a new value, the object's count is decremented. Any object with a reference count of zero can be garbage collected. When an object is garbage collected, any objects that it refers to have their reference counts decremented. In this way the garbage collection of one object may lead to the subsequent garbage collection of other objects.

An advantage of this approach is that a reference counting collector can run in small chunks of time closely interwoven with the execution of the program. This characteristic makes it particularly suitable for real-time environments where the program can't be interrupted for very long. A disadvantage is that reference counting does not detect cycles: two or more objects that refer to one another. An example of a cycle is a parent object that has a reference to a child object that has a reference back to the parent. These objects will never have a reference count of zero even though they may be unreachable by the roots of the executing program. Another disadvantage of reference counting is the overhead of incrementing and decrementing the reference count each time.

Because of the disadvantages inherent in the reference counting approach, this technique is currently out of favor. It is more likely that the Java virtual machines you encounter in the real world will use a tracing algorithm in their garbage-collected heaps.

2. Tracing Collectors:

Tracing garbage collectors trace out the graph of object references starting with the root nodes. Objects that are encountered during the trace are marked in some way. Marking is generally done by either setting flags in the objects themselves or by setting flags in a separate bitmap. After the trace is complete, unmarked objects are known to be unreachable and can be garbage collected.

The basic tracing algorithm is called "mark and sweep." This name refers to the two phases of the garbage collection process. In the mark phase, the garbage collector traverses the tree of references and marks each object it encounters. In the sweep phase, unmarked objects are freed, and the resulting memory is made available to the executing program. In the Java virtual machine, the sweep phase must include finalization of objects.

Cohesion and Coupling: Two OO Design Principles in Java

Cohesion and Coupling deal with the quality of an OO design. Generally, good OO design calls for loose coupling and high cohesion. The goals of OO designs are to make the application
  • Easy to Create
  • Easy to Maintain
  • Easy to Enhance

Coupling:

Coupling is the degree to which one class knows about another class. Let us consider two classes class A and class B. If class A knows class B through its interface only i.e it interacts with class B through its API then class A and class B are said to be loosely coupled.

If on the other hand class A apart from interacting class B by means of its interface also interacts through the non-interface stuff of class B then they are said to be tightly  coupled. Suppose the developer changes the class B‘s non-interface part i.e non API stuff then in case of loose coupling class A does not breakdown but tight coupling causes the class A to break.

So its always a good OO design principle to use loose coupling between the classes i.e all interactions between the objects in OO system should use the APIs. An aspect of good class and API design is that classes should be well encapsulated.

Cohesion:

Cohesion is used to indicate the degree to which a class has a single, well-focused purpose. Coupling is all about how classes interact with each other, on the other hand cohesion focuses on how single class is designed. Higher the cohesiveness of the class, better is the OO design.

Benefits of Higher Cohesion:
  • Highly cohesive classes are much easier to maintain and less frequently changed.
  • Such classes are more usable than others as they are designed with a well-focused purpose.