class_eval and instance_eval

Hey guys this is the most amazing and funny thing I have learnt in my life time. I started laughing like anything when I learnt how this behaves and things started going over my head for some time :)

Then I happened to watch Dave Thomas’s video on metaprogramming as many as thrice to really sink in whats going on. It’s so dam! confusing in start, I must say. But once you sink in the fact is that even all the classes in ruby are instances of the type Class at the end of the day, it all starts making sense.

So lets see what is this:

To start with lets say we have a class Animal {}

Now if I say, Animal.class_eval { # some code here may be a method definition}, what this will do is induce methods on the instance’s of the class Animal. Yes you read right, it’s the instances of the class Animal who will get methods defined inside the class_eval block of a class and not the class Animal itself.

Why so… if at all like this, then why is this stupid naming convention there to confuse the learners anyways. Exactly this went just now through your mind, right? So it did through my mind when I read it for the first time. But think it like this. Who is the receiver of the class_eval here. Receiver is the class Animal. So the methods will go in Animal class. Now if the methods go in the class Animal, then obviously they are available to the instances of Animal. RIGHT? :)

Now look at the other one, Animal.instace_eval {# some code goes here may be some method definition}. Now where are these methods goign to go. Lets analyze this in a logical manner. Who is the receiver here. Receiver is instance Animal. So the methods should go to the instance Animal and not the class Animal. Now, as I said a little while ago, every class is an instance of class Class. And therefore, there methods will go in the metaclass Animal (Represented as A’). This, in terms of Dave Thomas, is called ghost class or anonymous class which we cannot instantiate but does come in to play when any class is evaluated as an instance.

The above things would be easily get cleared to those who are familiar with the go-one-step-right for methods in ruby funda!

So, for those who do not know this, I would recommend watch the Dae Thomas’s videos on metaprograming. For those who hae forgotten and need some hint, read the following:

Ruby simply says, that the instances are behaviors are kept side by side, the object (receiver of the method call) being on the left and the methods that can be called on it are on the right side of it.

a ->(instance methods go in one step right to) Animal -> (class methods go in one step right to) Animal’

Still confusing, then u have really forgotten, go and read more :)

Thanks for reading (I am really lazy in giving good graphical examples, I am sorry for that. But that you might find out in some good book :) )

Ruby Metaprograming

The very hot and controversial topic I would say in the dynamic language world is Metaprograming. I am saying controversial, coz if not used properly it may lead to too many magics happening all across your application and it might become a nightmare to maintain it.

Definition : “The phenomenon of a piece of code writing another piece of code on the fly at the run time is metaprograming”

Definition seems to be very simple, but the implementation is not that simple, at least for me :)

I am just introduced to this (metaprogramming) world. Learnt about it, because I started following Dave Thomas, the pragmatic programmer. I watched the seven videos presented by him about the ruby metaprgramming, mixins, bindings, lamda, procs etc. I would say the videos are worth watching and so is the book Agile web Development with Rails by him. It’s very well written !! I must say.

So, I got exited after the videos and the book and couldn’t stop myself from penning down a few words about, what made me mad the most :  “Metaprograming”.

To start with lemme ask you a question “Have you ever wondered how come the things like att_reader or attr_accessor allow you to access the attributes of a particular modle in Ruby?“. Although Ruby as a language says that all the attributes of a model are inherently private. For example, let’s say I have a class

class Vehicle
attr_accessor :no_of_wheels
def initialize(no_of_wheels)
@no_of_wheels = no_of_wheels
end
end

vehicle = Vehicle.new(2)
puts “The vehicle has #{vehicle.no_of_wheels} wheels”
vehicle.no_of_wheels = 4
puts “The vehicle has #{vehicle.no_of_wheels} wheels”

Running the above program gives you the following output :

The vehicle has 2 wheels
The vehicle has 4 wheels

How is that possible!!! If you are a JAVA guy (like me), you will definately start pulling your hair when this is working inspite of not finding any getter or setter defind for the same in the class hirarchy any where. What is this magic. How come I am not getting the error on accessing the private instance variable @no_of_wheels in the Vehicle class. Hmmm… thats insane.

Here is Metaprogramming coming to play. In fact, what just happened here is that as soon as you say attr_accessor :instance_var_name, ruby inserts the gettetrs and setters as two instance methods on the fly in the Vehicle class for you. so in effect that single line of code makes the ruby class look like this:

class Vehicle
def initialize(no_of_wheels)
@no_of_wheels = no_of_wheels
end
def no_of_wheels() #getter
@no_of_wheels
end
def no_of_wheels=(no_of_wheels) #setter
@no_of_wheels = no_of_wheels
end
end

So at the run time, the no_of_wheels is available on the instances of the Vehicle class!! This is metaprogramming!

Now this also doesn’t happen out of the thin air. The code for the attr_accessor is present in Module class an is implemented in such a way that it generates the getters and setters for you.

OK, let’s do this. Let’s write our own implementation of the attribuet accessors. You will find mostly this example lying around all over the internet and the reason is probably that this is the most simply explained and makes most sense as the ruby newbie’s, like me, already see a lot of’em lying around as soon as they start with this monster language.

So here we go. In this example I’ll try to open the class Module and add my attribute accessor to it. Let’s call our attribute accessor as : access_vars

class Module
def getter_setter_for(*vars)
vars.each do |var|
class_eval
“def #{var}”
“@#{var}”
“end”
“def #{m}=(val)”
“@#{m}” = val”
“end”
end
end
end

And now in our class we can just say :

class Vehicle
getter_setter_for :no_of_wheels
def initialize(no_of_wheels)
@no_of_wheels = no_of_wheels
end
end

And this will just get us the getters and setters inserted on the fly when the class is loaded.
So here, the one line of code getter_setter_for or attr_accessor can write code on the fly. This is what metaprograming is!!

That’s it.

Secure Socket Layer : A Netscape Baby

Netscape created the first version (1.1) of the SSL protocol in 1994 and since then it has evolved and the final version 1.3 has been accepted as a standard in the web community for secure wire transfers. SSL is used to send data in encrypted data over the wire. Encryption is necessary when you are sending sensitive data like any funds transaction, credit card related data, or any sh*t in this world that you feel should be secured from an unautherised access and should reach in safe hands.

SSL is meant to ensure that your data reaches the safe hands. How does it all happens but? Before we can actually discuss the process lemme tell you some key terms that are you need to know for better understanding of the whole of the process.

Certificate: A certificate or digital certificate is an electronic document that is used to establish trust between the two parties (client and server) who want to communicate on the wire. It has following information which is used in establishing the authenticity and trust between two parties:

  • Information about the owner of the certificate, like e-mail address, owner’s name
  • Certificate usage, duration of validity
  • Resource location or Distinguished Name (DN) which includes the Common Name (CN) (web site address or e-mail address depending of the usage) and the certificate ID of the person who certifies (signs) this information.

Lets also have a look at how beautiful a certificate look:

Certificate:

Data:
Version: 3 (0×2)
Serial Number: 1 (0×1)
Signature Algorithm: md5WithRSAEncryption
Issuer: C=FJ, ST=Fiji, L=Sanjeev, O=SOPAC, OU=ICT, CN=SOPAC Root CA/Email=administrator@directi.com
Validity
Not Before: Nov 20 05:47:44 2001 GMT
Not After : Nov 20 05:47:44 2002 GMT
Subject: C=DI, ST=DIRECT, L=Mansha, O=DIRECT, OU=ICT, CN=www.directi.com/Email=administrator@directi.com
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
RSA Public Key: (1024 bit)
Modulus (1024 bit):
00:ba:54:2c:ab:88:74:aa:6b:35:a5:a9:c1:d0:5a:
9b:fb:6b:b5:71:bc:ef:d3:ab:15:cc:5b:75:73:36:
b8:01:d1:59:3f:c1:88:c0:33:91:04:f1:bf:1a:b4:
7a:c8:39:c2:89:1f:87:0f:91:19:81:09:46:0c:86:
08:d8:75:c4:6f:5a:98:4a:f9:f8:f7:38:24:fc:bd:
94:24:37:ab:f1:1c:d8:91:ee:fb:1b:9f:88:ba:25:
da:f6:21:7f:04:32:35:17:3d:36:1c:fb:b7:32:9e:
42:af:77:b6:25:1c:59:69:af:be:00:a1:f8:b0:1a:
6c:14:e2:ae:62:e7:6b:30:e9
Exponent: 65537 (0×10001)
X509v3 extensions:
X509v3 Basic Constraints:
CA:FALSE
Netscape Comment:
OpenSSL Generated Certificate
X509v3 Subject Key Identifier:
FE:04:46:ED:A0:15:BE:C1:4B:59:03:F8:2D:0D:ED:2A:E0:ED:F9:2F
X509v3 Authority Key Identifier:
keyid:E6:12:7C:3D:A1:02:E5:BA:1F:DA:9E:37:BE:E3:45:3E:9B:AE:E5:A6
DirName:/C=FJ/ST=Fiji/L=Suva/O=SOPAC/OU=ICT/CN=SOPAC Root CA/Email=administrator@directi.com
serial:00
Signature Algorithm: md5WithRSAEncryption
34:8d:fb:65:0b:85:5b:e2:44:09:f0:55:31:3b:29:2b:f4:fd:
aa:5f:db:b8:11:1a:c6:ab:33:67:59:c1:04:de:34:df:08:57:
2e:c6:60:dc:f7:d4:e2:f1:73:97:57:23:50:02:63:fc:78:96:
34:b3:ca:c4:1b:c5:4c:c8:16:69:bb:9c:4a:7e:00:19:48:62:
e2:51:ab:3a:fa:fd:88:cd:e0:9d:ef:67:50:da:fe:4b:13:c5:
0c:8c:fc:ad:6e:b5:ee:40:e3:fd:34:10:9f:ad:34:bd:db:06:
ed:09:3d:f2:a6:81:22:63:16:dc:ae:33:0c:70:fd:0a:6c:af:
bc:5a
—–BEGIN CERTIFICATE—–
MIIDoTCCAwqgAwIBAgIBATANBgkqhkiG9w0BAQQFADCBiTELMAkGA1UEBhMCRkox
DTALBgNVBAgTBEZpamkxDTALBgNVBAcTBFN1dmExDjAMBgNVBAoTBVNPUEFDMQww
CgYDVQQLEwNJQ1QxFjAUBgNVBAMTDVNPUEFDIFJvb3QgQ0ExJjAkBgkqhkiG9w0B
CQEWF2FkbWluaXN0cmF0b3JAc29wYWMub3JnMB4XDTAxMTEyMDA1NDc0NFoXDTAy
MTEyMDA1NDc0NFowgYkxCzAJBgNVBAYTAkZKMQ0wCwYDVQQIEwRGaWppMQ0wCwYD
VQQHEwRTdXZhMQ4wDAYDVQQKEwVTT1BBQzEMMAoGA1UECxMDSUNUMRYwFAYDVQQD
Ew13d3cuc29wYWMub3JnMSYwJAYJKoZIhvcNAQkBFhdhZG1pbmlzdHJhdG9yQHNv
cGFjLm9yZzCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAulQsq4h0qms1panB
0Fqb+2u1cbzv06sVzFt1cza4AdFZP8GIwDORBPG/GrR6yDnCiR+HD5EZgQlGDIYI
2HXEb1qYSvn49zgk/L2UJDer8RzYke77G5+IuiXa9iF/BDI1Fz02HPu3Mp5Cr3e2
JRxZaa++AKH4sBpsFOKuYudrMOkCAwEAAaOCARUwggERMAkGA1UdEwQCMAAwLAYJ
YIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1Ud
DgQWBBT+BEbtoBW+wUtZA/gtDe0q4O35LzCBtgYDVR0jBIGuMIGrgBTmEnw9oQLl
uh/anje+40U+m67lpqGBj6SBjDCBiTELMAkGA1UEBhMCRkoxDTALBgNVBAgTBEZp
amkxDTALBgNVBAcTBFN1dmExDjAMBgNVBAoTBVNPUEFDMQwwCgYDVQQLEwNJQ1Qx
FjAUBgNVBAMTDVNPUEFDIFJvb3QgQ0ExJjAkBgkqhkiG9w0BCQEWF2FkbWluaXN0
cmF0b3JAc29wYWMub3JnggEAMA0GCSqGSIb3DQEBBAUAA4GBADSN+2ULhVviRAnw
VTE7KSv0/apf27gRGsarM2dZwQTeNN8IVy7GYNz31OLxc5dXI1ACY/x4ljSzysQb
xUzIFmm7nEp+ABlIYuJRqzr6/YjN4J3vZ1Da/ksTxQyM/K1ute5A4/00EJ+tNL3b
Bu0JPfKmgSJjFtyuMwxw/Qpsr7xa
—–END CERTIFICATE—–

Besides the above information, you can notice that there is a public key information also in the certificate.

Public Key / Private Key: The key is based on prime numbers and their length in terms of bits ensures the difficulty of being able to decrypt the message without the having the key pairs. This is the key using which the data to be transferred on wire is encrypted. The process is known as Public-key cryptography, or asymmetric cryptography. By asymmetric we mean that the keys used to encrypt and decrypt the message are different. The private key is nothing different than the public key, the only difference being, as the name suggests, it is always kept secret. The message encrypted with the public key can only be decrypted using the private key and vice versa.

Now after knowing all these terms, I would like to pen down the simple steps in which the whole encryption/decryption process happens:

  1. A client (browser) requests a secure page (https).
  2. The web server first sends it’s public key enclosed within a certificate.
  3. The client checks that the certificate was issued by a trusted party (usually a trusted Certificate Authority), that the certificate is still valid, and that the certificate is related to the site contacted.
  4. The client uses the public key of the certificate to encrypt the data and sends it to the server.
  5. Teh server decrypts the message using the private key.
  6. The server then process the request and encrypts the result data using its private key and sends it back to the client.

The above type of encryption mechanism is known as Asymmetric Cryptography as the keys which are involved in encryption and decryption are different. But there is a flaw in the above process. The data that is being sent by the server back to the client, can be decrypted by any of the clients who have ever contacted the server. This is because all those clients would have the public key of the certificate (as you know the public key is distributed openly with the certificate). So basically the above process just offered one way protection of the data.

In order to solve this problem, the above process need to be modified a little. The solution is to have some key that only the client and the server know about and is unique for every single session. This is achieved by the process called Key Exchange. In this process after receiving the public key for the first time from the server certificate, the client generates a random key and encrypts it using the public key. This key is then sent to the server which server decrypts and thus they have a key which only the lint and the server know about. Any further communication between the client and the server happens using this key thereafter. That is the server then uses that key to encrypt the message sent to the client and the does the client. In fact the same key is used to decrypt the messages. So the same key is used for encryption and decryption both. And therefore this process is also known as Symmetric Cryptography. Since the same key is used this process o communication is relatively faster than the asymmetric one.

For the symmetric encryption, the above process is changed as follows:

4. The browser then uses the public key, to encrypt a random symmetric encryption key and sends it to the server with the encrypted URL required as well as other encrypted HTTP data.

5. The web server decrypts the symmetric encryption key using its private key and uses the symmetric key to decrypt the URL and HTTP data.

6. The web server sends back the requested html document and HTTP data encrypted with the symmetric key.

7. The browser decrypts the HTTP data and html document using the symmetric key and displays the information.

 

SSL Limitations:

  1. Point to Point Security: SSL only offers point to point security rather than end-to-end. By end to end we mean that when the data needs to go form one one end to the other passing through various nodes in between, where in the data needs to be processed by each node then it requires cumbersome task of encrypting and decrypting data at each point where any processing is required till the data reaches the final destination.
  2. Acts at the Transport layer and not on the Message layer: This means that SSL provides security only as long as the data is in the wire i.e. online and as soon as the is downloaded on the physical disk, the security is lost.
  3. Its atomic encryption: In SSL if you want to encrypt or secure a part of a long file and keep the rest as such, then it is not possible. It either does the whole data encryption or does not do at all for the whole data.

Anonymous Inner Class

Meri bheegi bheegi si palkon pe rah gaye, jaise mere sapne bikhar ke – ANAMIKA“. Indian readers can find the relevance here :-)

An anonymous inner class is one which does not have any name. Anonymous inner classes are created on the fly just in time. They introduce the weirdest looking java syntax. Following code shows an example of the anonymous inner class:

class Test
{

public void foo()
{

System.out.println(“main class foo method”);

}

public static void main(String[] args)
{

Test t = new Test()
{

public void foo()
{

System.out.println(“Anonymous class’s foo method”);

}

};

t.foo();

}

}

In this case look at the line in the main method that creates the instance of the Test class. Isn’t the syntax looking weired. Whats happening here is that we are actually creating an anonymous class which is a subclass of the Test class and overriding the foo() method. This is very useful when you just require to override one or two methods of a class, but do not want to create a new class all together for it. Here the anonymous class is created just-in-time and when the above program is run, it prints “Anonymous class’s foo method”.

Anonymous inner classes can also be used as an argument to a method call. The following code shows the same:

class Test
{

public void foo(Test t)
{

t.foo();

}

public void foo()
{

System.out.println(“main class’s foo called”);

}

public static void main(String[] args)
{

Test t = new Test();

t.foo(new Test()
{

public void foo()
{

System.out.println(“Anonymous class’s foo method”);

}

});

}

}

In the above we are calling an overloaded foo() method that takes an object of the Test class. We want to pass in an object that has a different behavior for the foo() method. So what we do is we create a just-in-time anonymous inner class and pass it as an argument to overloaded foo method. So when the no-arg foo method is called on the Test object from within the overloaded foo method, the anonymous inner class’s version of the no-arg foo method is called instead of the Test class’s original no-arg foo method. When this program is run it prints “Anonymous class’s foo method”

I would like to discuss one more case of the anonymous inner class case here. Sometimes you might require passing a just-in-time implementation of an interface which is not yet created. Consider a scenario that you have an interface and you do not have any class implementing that interface. You want to call a method that accepts the interface type. hat do you do? Simple ion this case also you would create an anonymous inner class and pass it as an argument to that method. The following code shows you the same:

class Test
{

public void foo(AnInterface i)
{

i.method1();

}

public static void main(String[] args)
{

Test t = new Test();t.foo(new AnInterface()

{

public void method1()
{

System.out.println(“Created just in time implementation class of the AnInterface”);

}

});

}

}

interface AnInterface
{

void method1();

}

Here we just created an anonymous inner class that is an implementation of the AnInterface interface and passed it to the method foo which takes the AnInterface type as a parameter. You can see that the anonymous inner class has to give the implement the method1() present in the AnInterface (obviously :-) ). When this program is run, it prints “Created just in time implementation class of the AnInterface”.

This is it for the anonymous inner classes :-) . Will keep coming up with more topics till the time I finish preparing for SCJP :-)

Method-Local Inner Classes

Method local inner class is that class which is declared within the curly braces of a method as follows:

class OuterClass
{

public void method1()
{

class MethodLocalInnerClass
{

public void innerClassMethod()
{
}

}

}

}

same as the method method1() can. The The above class MethodLocalInnerClass declared inside the method method1() is called method local inner class. As the name suggests this class is in the scope of the method only and can access any member of the OuterClass. Important point here is that the MethodLocalInnerClass class cannot use any of the local variables of the method1() (except those which have been marked final). the reason being that the method resides on the stack and as soon as the method life is over all the local variables of the method are also vanished. Now imagine if the method local inner class is using the method methods1()’s local variables and setting them as value of one of its instance variables and then method method1() passes an object of the MethodLocalInnerClass in another method’s invocation as a parameter. In that case the local variable will also be passed as a part of the MethodLocalInnerClass object. Now if the method1’s execution completes, then the local variables are vanished and in that case the object of the MethodLocalInnerClass will be carrying a reference to a variable which does not even exist on the stack anymore.

The following code will explain this scenario more clearly:

public class Test2
{

public static void main(String[] args)
{

System.out.println(foo().toString());

}
static Object foo()
{

Object localVar = new Object();
class Foo
{

public String toString()
{

return “Hi:”+localVar.toString();

}

}
return new Foo();

}

}

If you look properly, you can see that the foo() method of the Test class is returning a reference of the method local inner class Foo declared in the foo() method. So now you can call the toStrin() method of the Foo class from outside the method foo(). So whats the problem here. The problem is that the toString() method of the Foo class is using the local variable localVar which does not exists anymore as the method foo() has already returned and its stack has already been blown up. So this would not even compile. The only solution to make this code compilable is to make the localVar being used in the method local inner class Foo class as final.

One more thing about the method local inner class, that an instance of the method local inner class should be made after full declaration of the method local inner class. The following code will explain what I want to say here:

class OuterClass
{

public void method1()
{

class MethodLocalInnerClass
{

public void innerClassMethod()
{
}

}
MethodLocalInnerClass mlic = new MethodLocalInnerClass(); // remember this instantiation of the method //local inner class came after the class declaration.

}

}

If you try to create an instance before the class declaration, the code won’t compile for obvious reasons here :-)
That’s it for the method local inner classes.

JAVA Inner Classes

One class one responsibility : Cohesive Class. Got it. Its good of course“.

But what about the situation when there is a totally different set of responsibilities that actually require to be together as one unit and at the same time should be tightly bound to your class. The inner classes serve the purpose of having class that has an intimate relationship with your class while your class is hidden from others. This is because the inner class is actually a part of your class and has access to all the members of the class including even the members that have been marked private as any other other instance method would have. The inner classes are declared within the outer classes with curly braces as follows:

class OuterClass
{

class InnerClass { }

}

The InnerClass in the above code is an inner class of the OuterClass class. If you compile the outer class, you will get two classes instead of one as follows:

OuterClass.class
OuterClass$InnerClass.class

As you can see that the inner class is associated with the inner class name with a $ sign joining the name of the inner class with the outer class. This is so true to the behavior also, as the inner class would never be accessible without the existence of the outer class. As in an instance of the inner class does not make any sense without an associated instance of the outer class. Moreover you cannot say like java OuterClass$InnerClass to run the main() method in the InnerClass because the InnerClass cannot have any static declaration (main() is static of course !!).

Instantiating Inner Classes: As I already said, the inner class instance does not make any sense without the instance of the outer class to which it is associated or tied to, so in order to instantiate any inner class, you need an instance of the outer class as well. You may instantiate the inner class from within the outer class or outside the outer class.

Instantiating InnerClass From Within any non-static method of the OuterClass: This is fairly simple. As you would know that the outer class methods always has a this reference (except the static methods), so in order to instantiate you can simply write

InnerClass in = new InnerClass();

from any non-static method of the OuterClass.

Instantiating InnerClass From Outside the OuterClass or From a static method Within the OuterClass: In order to instantiate the InnerClass from within a static method of the OuterClass or from anywhere outside the OuterClass you would first need to make a reference of the OuterClass as follows:

OuterClass outerClass = new OuterClass();
OuterClass.InnerClass inc =
outerClass.new InnerClass();

That’s it for now on Inner Classes. there is a lot more to tell about it, but next time (but very soon I guess).

SCJP Exam Preparation

Hi all,

I am preparing for the SCJP exam and started the preparation about 3 months back. Its been a very tough decision for me to kick-start the preparation but then after one of my friends made me realize that I am wasting my precious time and that it is important to get certified ASAP, I started the preparation. I am going to tell you about the journey till now (I have still not given the certification exam). In my company the certification is compulsory though and I need to get certified by the end March 2008. I guess there is enough time till then. But you never know. Sometimes people might take years to get certified. Ok what I am going to do is to update this post till I get certified regrading what decisions I made in my journey to get certified :-)

1. So let me tell you that I finished Kathie Sierra’s book “SCJP Sun Certified Programmer for Java 5 Study Guide (Exam 310-055) (known best book for the certification as far as I know). This book has got everything that you might need to clear the certification with good score. I have my friends her in the company most of who have scored more than 90%in the exam (one has has also scored 100% :-) ). So I finished this book first time in about 20 days of time. There are a total of 10 chapters.

2. Although I started taking the mock tests that are freely available on the Internet. I tried Enthuware and whizlabs tests. But I did not get the expected score (average 70%). The reason obviously being that I probably did not remember all the details properly that are there in the book. So today I decided to re-read the book and then probably will take the mock exams again. Let’s see what happens…….

3. I am glad to announce that today I am nearly going to complete the whole book. I have already read till the 9th chapter half way and hope o complete the book by end of next weak (I would have completed it this weekend itself but then I have some prior appointments, so won’t be able to make it.)

“Protected” and “Default” JAVA Access Modifiers

I guess that these two are the most confusing and misunderstood access modifiers amongst all other JAVA access modifiers for most of the average java programmers till date . I would like to take one by one. Lets start with “default first”

Default: Default access modifier is no-modifier. i.e when you do not specify any access modifier explicitly for a method, a variable or a class ( FYI : a top-level class can only be default or public access modifiers) it gets the default access. Default access also means “package-level” access. That means a default member can be accessed only inside the same package in which the member is declared.

Protected: Protected access modifier is the a little tricky and you can say is a superset of the default access modifier. Protected members are same as the default members as far as the access in the same package is concerned. The difference is that, the protected members are also accessible to the subclasses of the class in which the member is declared which are outside the package in which the parent class is present. But these protected members are “accessible outside the package only through inheritance“. i.e you can access a protected member of a class in its subclass present in some other package directly as if the member is present in the subclass itself. But that protected member will not be accessible in the subclass outside the package by using parent class’s reference. Confused with language ? Take an example. Say there is class “Super” in package A containing a protected integer variable “protected int x” and it’s subclass “Sub” in package B. The following would be a legal statement in a class B:

System.out.println(x); // valid

Whereas following would be an illegal statement:

System.out.println(new Super().x);

// invalid, as you cannot use parent class reference to access the protected member outside the package.

Once the child gets access to the parent class’s protected member, it becomes private (or rather I would say a special private member which can be inherited by the subclasses of the subclass) member of the subclass.

I hope that clarifies the difference between the private and default access modifiers. But if you have a question still about it, please leave a comment and I’ll get back to you. :-)

thx

Posted in Java. 11 Comments »

Java Serialization

Java Serialization is used to persist Java objects. The persistence is achieved by writing the object state to an external system (it can be a file database etc). Once you have written an object, you can get the object back any time by reading the object back from that external source. This feature is mainly required when you are working in a distributed environment where your application is running in more than one JVM’s and you need to pass the objects from one JVM to another.

Serialization is achieved by using JAVA interface named “Serializable”. This is a marker interface (An interface that is just used to mark any class of being a particular type to let the JVM know that it is of that type. A marker interface does not contain any methods). We need to make any class implement the serializable interface (or inherit from a serializable class) if we want to persists the objects of that class. Its tells the JVM that the objects of this class can be serialized.

How to Serialize: After making any class implement the serializable interface, we need to write following few lines of code to actually serialize the objects of that class. Consider the following class that you want top serialize:

import java.io.*;
class Cat implements Serializable { }

public class SerializeCat

{

public static void main(String[] args) {

Cat c = new Cat();// serialization of the Cat object c, starts here
try

{

FileOutputStream fs = new FileOutputStream(“testSer.ser”);
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();

}

catch (Exception e)

{

e.printStackTrace();

}

// deserialization of the Cat object c, starts here
try

{

FileInputStream fis = new FileInputStream(“testSer.ser”);
ObjectInputStream ois = new ObjectInputStream(fis);
c = (Cat) ois.readObject();
ois.close();

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

You can see that the serialization and deserialization requires calling the readObject() and writeObject() methods. These methods are present in the ObjectOutputStream and ObjectInputStream classes respectively. These methods actually perform the serialization of the object passed as the parameter. While serializing the object the current state of the object is saved. Here we are saving the state of the object by writing it to a file testSer.ser. Then we can restore or deserialize the same state of the object by using the ObjectInputStream’s readObject method. Note that here, since the readObejct() method returns the type Object so we need to cast the object to the required type explicitly.

Not everything might be serializable, make it Transient: If your class contains reference variables of other non serialzable classes, then while serializing the object of your class you would not be able to save the value or state of that reference variable of non serializable class. If you try saving you will get the following run time exception: java.io.NotSerializableException In this scenario, you have got following two choices:

1. To declare the reference variable transient by prefixing the variable declaration by keyword transient: In this case the state of the non-serializable reference will not be saved while saving the serializing the object of your class. Remember in this case, when the you deserialize the object of your class the value of the transient marked references of your class will be null as during deserialization the constructor of the class is never called.

2. To override the readObject and wrietObject methods of the ObjectInputStream and ObjectOutputStream classes respectively and save the state of the reference of the non-seriazable class.
In this case, you will have to call the defaultReadObject() and defaultWriteObject() methods in the readObeject() and writeObject() methods respectively and these calls should be the first line in the readObeject() and writeObject() methods. The methods should have the following signature only:

private void writeObject(ObjectOutputStream os)

{

// your code for saving the non serializable reference variables

}
private void readObject(ObjectInputStream os)

{

// your code to read the non serializable reference

}

After that you will have to specify how to save the state of the non serializable references of your class while saving the object of your class.

JAVA Threads : Join() and wait() methods

We all know that there are a lot of things in JAVA and to all of us (or rather to all the people I met till date, feel that Threads are the most tricky to understand as far as their real time behavior is concerned). This topic is about the behavior of the join method and its comparison to the wait method. I am making this comparison because the join method calls the wait method internally.

Wait() : If a thread calls wait method on an object (obliviously that thread must already have acquired the lock of the object it is calling the wait method on, otherwise a runtime exception is thrown), that thread releases the object and goes to the waiting state. So in all the wait call forces the thread to release the object it is calling wait on.

Join() : If a thread (name it T1) calls the join method on another Thread (remember the wait method is in the Object class and the join method is specific to the Thread class and is present in the Thread class) named T2, then T1 waits for T2 to complete its execution before it continues from that point. Now think what will happen. Will thread T1 leave the locks on the object it has acquired lock on or not ? If we consider the fact that the join method internally calls the wait method the answer that pops up immediately is that “obviously it should leave the lock“, which is WRONG !!!!

For a moment lets assume this answer is correct. Now imagine the scenario, where the thread T1 has called this wait inside a synchronized lock where it has acquired a lock on a String object “abc” and has called the T2.join() inside this block. Now as this call has been made by T1 inside the synchronized block, it obviously means that it needs the lock on the “abc” object to continue the execution further. If T1 has released the lock on “abc” object it will be rescheduled by the thread scheduler to acquire lock on “abc”. But it is not guaranteed tha it will acquire the lock as soon as the thread T2 completes. So in this case some other thread T3 might acquire the lock on “abc” and enter the same synchronized block which the thread T1 already half way !!!! So if the join method makes the calling thread leave the locks, then whole whole use of the synchronized block is ruined.

Wait() inside Join() mystery : The wait method call in side the join method implementation is being called on “this” i.e the thread on which join was called (T2). That wait call does not have to do anything with the calling thread (T1). That means the join call does not causes the calling thread to release a lock on any object and it simply makes it wait till the thread it called join on completes its execution keeping all the locks it already acquired.

I tried the above theory with the following example code:

class AThread extends Thread
{

public void run()
{

System.out.println(“T2 started”);
synchronized (Test2.lock)

{

System.out.println(“Hi hello”);

}

}

}

public class Test implements Runnable
{

public static final String lock = “lock”;
public static final String lock1 = “lock1″;
static Test t = new Test();
static Thread T1 = new Thread(t, “Thread T1″);
static AThread T2 = new AThread();

public static void main(String[] args)
{

T1.start();
Thread.yield();
T2.start();

}

public void run()
{

synchronized (lock)

{

System.out.println(“T1 started”);
try
{

System.out.println(“waiting for T2 to join”);
T2.join();

}
catch (InterruptedException e)
{

System.out.println(“e.getMessage() = ” + e.getMessage());

}
System.out.println(“T1 ended”);

}

}

}

Running the above program produces the following output:

T1 started
T2 started
waiting for T2 to join

And the execution locks here as Thread T2 tries o acquire lock on the “lock” object which has already been acquired by thread T1 and as T1 has called join on T2, T1 does not leave the lock on the “lock” object and thus a deadlock occurs.

Note: The call to the yield() between the cal to the start() method of T1 and T2 is just to increase the possibility of starting the T1 thread and go a lil ahead on the execution line before the ThreadT2 is started. If the thread T2 starts first, then there would br no deadlock here as the lock will be gained by thread T1 and the execution will complete smoothly. Remember the above example is a 99% deadlock situation and so you should always avoid such situations.

Posted in Java. 2 Comments »