Sunday, December 19, 2010

Call me!


Today you will have a great occasion to call someone you would never expect to call... a thread. We talked already about the concurrency on the blog: Threads part 1: The basics and Threads part 2: functions overview. But the problem with the previous solution to achieve simultaneous computation is the lack of explicit mechanism to retrieve the result from a thread. As luck would have it, since Java 1.5 we have an access to a new interface – Callable. In comparison to Runnable there are a few significant differences:
  • with Callable you can easily return a result of another execution thread.
  • with Callable you can throw checked exceptions.
  • with Callable you have to use a thread executor.
So far so good. Now, to get more familiar with it, let's have a look at some code:

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


class Computation implements Callable<Integer> {

@Override
public Integer call() throws Exception {
int result = 0;
for(int i = 0; i < 10000; i++) {
for(int j = 0; j < 100000; j++) {
// Some taught computation
result += (i * j) - (i * j) + 1;
}
}
return result;
}

}

public class CallableExample {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(5);
Future<Integer> f1 = pool.submit(new Computation());
for(int i = 0; i < 10; i++) {
System.out.println(i);
}
try {
System.out.println(f1.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
pool.shutdown();
}
}

Ok, there are a few new elements regarding Callable. First of all, if we implement the Callable interface, we have to implement T call() method. This is where the action takes place, it's a method corresponding to the run() method from Runnable interface. And the other important thing – it's the place where we can throw an exception (Exception or any subclass).
When the class implementing Callable interface is ready, we can instantiate it and run through a submit() method of a thread executor what happens in line 27. The submit() method will return some implementation of a Future interface. It represents the thread's computation and provides a few useful methods, among others:
boolean isDone();
which returns true if the task is completed.
T get()
which returns a result of a task of type T, or if the task is not completed yet it waits until it's finished. Actually this could be achieved with a wait() method using a Runnable interface and calling it on the instance of a thread from the main execution thread.

And that's it. I'm sure that the above information and the sample code will let you use the Callable interface in appropriate way.

Wednesday, December 15, 2010

Type erasure in Java.

Probably every Java developer knows what type erasure is. In Oracle tutorial on Type Erasure we can read:

When a generic type is instantiated, the compiler translates those types by a technique called type erasure — a process where the compiler removes all information related to type parameters and type arguments within a class or method. Type erasure enables Java applications that use generics to maintain binary compatibility with Java libraries and applications that were created before generics.

The generic types are only for the compile time - after the type checking they are removed and gone for good, for sake of legacy code. Are they really? Let's have a look at the code I just wrote:

import java.lang.reflect.Field;   
import java.lang.reflect.ParameterizedType;   
import java.lang.reflect.Type;   
  
class P1 {}   
class P2 {}   
class P3 {}   
  
class A<T1, T2, T3> { }   
  
public class Gen2 {    

    A<P1, Integer, P3> genTest = new A<P1, Integer, P3>();   
    public static void main(String[] args) throws Exception {      
        ParameterizedType genTestField = (ParameterizedType)Gen2.class.getDeclaredField("genTest").getGenericType();   
        for(Type type : genTestField.getActualTypeArguments() ) {   
            System.out.println(type);   
        }   
    }   


In the above code, we define a generic class A that can be parametrized - in the line 13 we instantiate this class with parameters P1, Integer and P3. And now,
through a reflection of Gen2 class and methods getDeclaredField(String) and getGenericType() we can elicit the parameters used during instantiating generic class A!
The code will print:
class P1
class java.lang.Integer
class P3
So in this way we can get exactly the generic parameters that were used. How this can be accomplished? As I already wrote, through a reflection. When we open a compiled Gen2.class file we can see a section "Signature":
Signature LA<LP1;Ljava/lang/Integer;LP3;>;
which shows the types that we were interested in. So apparently it seems that this information is not completely removed after the compilation time. From the bytecode yes, but in the .class file the information is still available!
In my opinion it's a very interesting and important example especially when we can read in many places that after the compilation we can't get the parameters anymore! Hope it was at least a little bit inspiring and encouraged you to read more on the reflection mechanism.

Saturday, December 11, 2010

String's split() method.


This will be short. Recently I had to use this simple String class method when developing a parser for some pdf documents. Everything was going well until one moment. In the document, among others I had to elicit a range value which was given in the format x..y (for instance, 1..32). After getting the string 1..32 I wanted to use split method to separate the bounds. So in the code it could look like this:


String range = "1..32";
String[] bounds = range.split("..");

But that didn't work! Why? The answer is very simple. The String's split method takes a regex expression as an argument! And in Java "." (a dot) in regex means any character. So that's why the returned array was empty! To solve it we have to use "\\" between any special regex character if we want it to be treated as a string character. So we should change the above code to:


String range = "1..32";
String[] bounds = range.split("\\.\\.");

That's simple! So remember: split's argument = regex expression! Wish all my readers remember this both on the exam and during the work with Java code.

Sunday, November 28, 2010

Java 7, where are you?


That's right. On the December 11 it will be round 4 years since the first release of Java 6. And I have to admit that it's quiet a long time in comparison to the previous versions. Ok, why don't have a little history lesson right now? Let's go back in time to end of 90s. Right before Christmas period, in '98, on December 8 Java 1.2 is published. A year and a half (May 8, 2000) after this Java 1.3 kicks in. Then again, not even 2 years and we had the Java 1.4 (February 6, 2002). And it keeps going. September 30, 2004 – Java 1.5, December 11, 2006 – 1.6. And today we have November 28 2010 and there is still no Java 7! Nearly 4 years! Of course we had plenty updates to Java 6 (more precisely 22) but I still claim it's a long time. You may probably wonder that there are lots of new features and important changes coming up soon. The reality though, is a little bit different. Soon – yes, in the mid of 2011. Lots and important? Let's have a look. As for the Java 7 we got 2 major Java Specification Requests. JSR #334 Small Enhancements to the Java Programming Language and JSR #335 Lambda Expressions for the Java Programming Language. In a nutshell, the #334 introduces the following features:
  • Strings in switch
  • Binary integral literals and underscores in numeric literals
  • Multi-catch and more precise rethrow
  • Improved Type Inference for Generic Instance Creation (diamond)
  • try-with-resources statement
  • Simplified Varargs Method Invocation
I don't say these changes are not cool. They actually are. For instance the Diamond syntax will let you replace
 Map<String, ArrayList<Integer>> m = new LinkedHashMap<String, ArrayList<Integer>>();  
with this:
 Map<String, ArrayList<Integer>> m = new LinkedHashMap<>();  

Another interesting feature is “try-with-resources statement”. You may wonder what this is. Have a look at the following example (sorry for the lack of proper code formatting but for some reason it doesn't work with this code):
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();

} finally {
br.close();
}
With the automatic resource management statement it will look like this:
try (BufferedReader br = new BufferedReader(new FileReader(path)) {
return br.readLine();
}
This new enhanced try clause will automatically close the resource after the try block so in this case it will never happen that the programmer forgets about it. Oh, and any sorts of streams are welcome in the new try plus you can have more than one.

And my most favourite – the second point. You will be able to use underscores in numeric literals, like this:
int howCoolIsThis = 1_000_000;
No kidding. That's one of the points proposed for the Java 7 specification.

Ok. Let's go to the big one. Lambda expressions! Present in the huge rival of Java – C# and also in other languages like PHP or Javascript. And now very likely to be introduced to Java 7. Here is the glimpse of the request:
  • Lambda Expressions
  • SAM Conversion
  • Method References
  • Virtual Extension Methods
As for me, this is a real boost of Java 7 and the feature that will make an actual difference. Because let's be honest, the changes from the JSR #334 are really minor. Of course, they all are very useful (maybe except the underscore thing...), especially the Diamond syntax and will lead to the better quality of code but aren't these too few changes for 4 years?

Sunday, October 31, 2010

And here it is - certification summary!


Well, I must admit that it's been some time since the last article but I was really overwhelmed recently – I had to accommodate in a new apartment, settle down all the things at university and finally I have started to work as a Java Software Developer. But anyway, now all the issues are resolved and I'm back to blogging again!

So today I would like to make a summary of OCPJP certification. First of all, I'm really glad that I've taken upon this endeavor. I have learnt many new things about Java that I didn't use before. Actually I'm not sure if I will ever use it but it's good to know it anyway ;-). And as luck would have it, I already have noticed how has my marked value increased. I did mention that I got a job, didn't I? ;-) Alright but you might probably want to know what I did in preparation for this exam. So obviously on the first place there is a book, the only one, don't even think about getting any other - SCJP Sun Certified Programmer for Java 6 Exam. I read it twice. The first time was a quick review of the book and getting familiar with some completely new areas. The second time though was much more careful and full of experiments with the code. And that is really vital! Experiment with the code – without this you will score much lower than you could if you did it. I know, it takes some time but trust me on that, it's really worth it. Ok, so let's assume that you already read the book, as many times as you wanted and you are wondering what next... Well, in my case it was a series of mock tests. Mostly by Whizlab (http://www.whizlabs.com/scjp/certification-exam.html). But in this place I have one more important tip. After solving a mock test also do some experiments with the code in exercises, especially the ones that were not correct. And I guess that's all! If you do more or less what I've described I'm sure you will do well on the exam!

As for me, my next goal on the Oracle Certification path is Oracle Certified Professional, Java EE 5 Web Component Developer! Soon, you will be able to follow my preparation's activities to this exam!

Saturday, September 11, 2010

Oracle Certified Professional Java SE 6 Programmer exam passed!


Yes, that's it! On the 6th of September I made it with 95% score. Not bad at all! It means 57 out of 60 questions answered correctly! Frankly speaking, the exam didn't seem to be easy - many questions required me to think deeply not as it was with the Whizlabs' tests. Even though, I had had some spare time left at the end to review all the questions and afterwards could hit the magic button "end" which surprisingly... ended the exam! But don't worry! The fact that I passed the exam doesn't mean that I will stop posting the articles related to it. I have a list of topics that I want to bring up here and after my short holidays that I'm on right now I will resume writing! I will also say something more about my scores of the exam and add some important notes that might be helpful for other people preparing to become certified!


Friday, August 27, 2010

Utility methods of wrapper classes.

Wrapper classes basically have two purposes: to wrap a primitive and to provide a set of utility functions dealing with some conversions. In this article I will focus on the latter objective.

The first function that I will cover here is a static valueOf() method. It takes as an argument a string and converts it to the desired wrapper object. In most cases you can also provide a second parameter that is an int radix which indicates the base of the first parameter. The valueOf() method is provided in most of the wrapper classes (except Character). It throws a NumberFormatException (it is not checked so you don't have to declare it) if the string provided can't be converted. Here are some legal uses of it:
Integer i1 = Integer.valueOf("3");
Integer i2 = Integer.valueOf(123);
Float f = Float.valueOf("2.2");

The second method is xxxValue() where in the place of xxx we can put any primitive. This function converts the value of a wrapped object to a primitive. The following code shows a few examples of how we should use it:
Float f = Float.valueOf("5.5");
byte b = f.byteValue();
short s = f.shortValue();
double d = f.doubleValue();

The next function that is important to remember is parseXXX(). It is static and takes a string as an argument and parses it into an appropriate primitive. It also throws NumberFormatException in case when the string arument is not well formated. Let's have a look at the following demonstration code:
double d = Double.parseDouble("123.456");
int i = Integer.parseInt("345");
byte b = Byte.parseByte("127");

And that's it! Three useful and important methods that we should know for the exam!

Wednesday, August 25, 2010

No more Sun Certified Java Programmer!

Erm... nearly. If you want to become one you should simply hurry up. You have 7 days for that and starting on 1st September you will be named Oracle Certified Professional Java SE 6 Programmer. That's another outcome of the acquisition Sun by Oracle that has had place at the beginning of this year.

As for me the name of the certificate doesn't really matter but what actually pops up in my mind is the question whether and when the employers will become familiar with the new name. Let's be honest - one of the reasons of why we become certified is the fact that it adds a new valuable element to our CV. But for this, the potential employer must be familiar with the title. Recently I read on a forum that Oracle sends some newsletters about the naming changes for the interested people (you probably need an account in the Oracle's Education Center) but for sure it will take some time to spread the word.

Nevertheless, below is the link to Oracle's website with additional information and names of the other exams. Yes! All the names has been changed!

Oracle Certification Program

Friday, August 20, 2010

Assignments.

By the title I actually mean the 3rd chapter of the K&B SCJP book. I have to admit that it was really surprising. I have learnt many new things that I was completly unaware of. Of course, in the real projects, when you use some IDE it's nearly impossible to make mistakes of this sort but on the exam they can be very savage. So below you will find some important points from this chapter that you really should pay attention to, during the exam.

First, we'll talk about the literals. Remember that every integer literal is an int. So there is no problem if we want to do the following assignments:
int a = 5; (fits well)
long b = 6; (fits well since long is bigger than int)
but what if we try to assign the integer literal (so an int) to the smaller type? Let's have a look!
byte c = 7;
And yeah, there is still no problem. That's of course good for us but basing on the above that shouldn't work. Well, that happens because the compiler makes an implicit cast so in fact, it looks like this:
byte c = (byte)7;
Alright. That's very convenient for us. But this implicit cast is applied only to literals! So this is not going to work:
int a = 5;
byte b = a;
To compile the code consisting of the above assignments you need to do an explicit cast:
int a = 5;
byte b = (byte)a;
Also keep in mind the following rule. The result of any expression involving an int or anything smaller, like byte and short will result in an int! So the following will... not compile!
byte a = 5;
byte b = 1;
byte c = a + b;
You need to put an explicit cast! One more thing about the floating points literals. They are always doubles. And here the compiler won't make an implicit cast, the following code will not compile:
float d = 2.5;
Instead you should write:
float d = (float)2.5;
Or mark that what you mean is really a float by adding and f or F at the end of the literal:\
float d = 2.5f;
Ok, that's it for the literals! Now let's move on to the primitive casting.
First of all, it's important to remember that the implicit cast happens when we assing a smaller to a bigger. So for instance:
int a = 5;
byte b = (byte)a;
long c = 'a' + 'b';

a = b;
c = a;
c = b;
These are all legal assignments. But the followings are not:
b = a;
b = c;
a = c;
And what do we need? An explicit cast!
b = (byte)a;
b = (byte)c;
a = (int)c;
Et voila monsieur! Also the same thing happens with floating points. All the following are legal:
double d = 2.5;
float f = 3.4f;
int i = 12;
long l = 45;

d = l; // assigning long to double
d = f; // assigning float to double
f = i; // assigning integer to float
But in case when a truncation may occur we have to make an explicit cast otherwise our code will produce an error.
The followings are legal but the cast is necessary:
double d = 2.5;
float f = 3.4f;
int i = 12;
long l = 45;

f = (float)d;
i = (int)f;
l = (long)d;
That's a piece of cake but I'm sure that you've found here something new and interesting for you!

Thursday, August 19, 2010

Downcasting and a compiler.

Today I will write shortly about the downcasting and especially about the way the compiler can assist us while doing this. Actually it can't do a lot. It trusts us when we do the downcast that it is actually possible. Let's consider this example:
 class Vehicle {}
class Car extends Vehicle {}
public class Sfield {
public static void main(String[] args) {
Vehicle v = new Vehicle();
Car c = (Car)v;
}
}

This example compiles without any problem. But what will happen is... a java.lang.ClassCastException thrown! However there is one situation, when the compiler can help us. If we try to downcast the class from the different inheritance tree the compiler will let us know about it during the compilation time and not the runtime! For instance:
 class Vehicle {}
class Car extends Vehicle {}
public class Sfield {
public static void main(String[] args) {
String v = new String("Vehicle");
Car c = (Car)v;
}
}

So if the compiler knows that the downcast will not work for sure it will manifest it with:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot cast from String to Car
But in the first example it might happen that the v references to the Car object. But it was not possible to verify this at the compilation time.

Monday, August 16, 2010

Inheritance and the default superclass constructor.

In this short article I will write about the situation, when we extend some class but its default constructor is not accesible for us. For example it has a private modifier or a default one and we are in a different package. If this is a case, we have to remember to use another (accessible) superclass constructor in our subclass constructor. If we don't do it, a compiler will try to insert a call to the default constructor super() which obviously will not work. Below is an example of this:
 class U1 {
private U1() { }
public U1(int x) { }
}
class U2 extends U1 {
U2() {
System.out.println("U2 construction...");
}
}

To mitigate the situation we should explicitly use the public but not default constructor as in the following code:
 class U1 {
private U1() { }
public U1(int x) { }
}
class U2 extends U1 {
U2() {
super(5);
System.out.println("U2 construction...");
}
}

Sunday, August 15, 2010

Static modifier.

Hello there! Static modifier is a very wide subject and obviously I'm not going to explain everything now. But you will find here a couple of interesting notes!

First of all we will talk about static variables. Remember! There is only one static variable for the whole class and all its subclasses and their instances! The following example illustrates it:
 class T1 {
static int a = 5;
}
class T2 extends T1 { }
public class Sfield {
public static void main(String[] args) {
T2.a = 6;
System.out.println(T1.a);
System.out.println(T2.a);
}
}

And the output is:
6
6
(Luckily there is no third 6 since it could have got scary)
What would happen though, if in T2 we define again the static int a? Let's have a look:
 class T1 {
static int a = 5;
}
class T2 extends T1 {
static int a = 6;
}
public class Sfield {
public static void main(String[] args) {
System.out.println(T1.a);
System.out.println(T2.a);
}
}

And the output of this will be:
5
6
So now apparently we have different static fields for each class and its instances. What does matter here, is the type of the reference variable that we try to access the member.

The similar thing happens with static methods. It is important to remember that static methods can not be overridden. We can though, redefine them!
 class R1 {
static void say() {
System.out.println("R1");
}
}
class R2 extends R1 {
static void say() {
System.out.println("R2");
}
}
public class Sfield {
public static void main(String[] args) {
R1.say();
R2.say();
}
}

And the output will be:
R1
R2
But still it's not an override but a redefinition!

Thursday, August 12, 2010

Enumerate it!

Today I will write about really cool thing in Java that is enum type. If you used to code in C/C++ you may wonder what is so cool about it since it's really simple and straightforward. Well, in Java things are a little bit different. Of course, you can use enums in the way that you know from C, for example:
 enum Colour {RED, YELLOW, BLUE}

but that's not really what I'm gonna cover here. Enums in Java are much more than that. They are some kind of a class so you can actually add constructors, instance variables, methods and one more thingy.
Let's say that you would like somehow associate the enum value with a string that says something more about the colour. We can do it in this way:
 enum Colour {
RED("bloody"), YELLOW("shiny"), BLUE("sea");
String info;
Colour(String info) {
this.info = info;
}
}
public class Woo {
public static void main(String[] args) {
for(Colour c: Colour.values()) {
System.out.println(c.info + " " + c);
}
}
}

So in the above code we define our Colour enum. It is different from the previous example from the very beginning - we define our values but in brackets we put our additional information. This can happen because later on we define a constructor that can handle this. We also define a "info" field to which, the constructor will pass given reference. In the main() function we also use the static method of enum's values() which returns an array of previously defined enums. Please note that the order is exactly the same as in the definition.

Alright, at the beginning I mentioned some enum's features and among others there was some thingy thing. In fact, what I meant is constant specific class body. To explain it, imagine that you would like to even add some more information about the colours and that the only thing you can say more about them is "mmm..." (cause they're so good so you'd like to hoover'em) except the BLUE one. With the blue you would like to say add "extreamly". To cope with it we can define a method that will return the string consisting of "extreamly". But wait! We don't want to get the same information for all enums. In case of the BLUE we want to have "extreamly". And here comes constant specific class body where we can override the method and make it specific to the chosen enum value. The important thing here is that it can be only used for overriding the methods defined in the enum. If there is no method in the enum, you can put any in the constant specific class body.
And here is the code for the example just described:
 enum Colour {
RED("bloody"),
YELLOW("shiny"),
BLUE("sea") {
public String moreInfo() {
return "extreamly";
}
};
String info;
Colour(String info) {
this.info = info;
}
public String moreInfo() {
return "mmm...";
}
}
public class Woo {
public static void main(String[] args) {
for(Colour c: Colour.values()) {
System.out.println(c.moreInfo() + " " + c.info + " " + c);
}
}
}

Tuesday, August 10, 2010

In the protected way...

You may wonder what do I mean. No, I'm certainly not gonna write about driving a bullet proof limo or wearing this kind of vest. Protected sex? No, not really. Of course it's not like I'm supporting having unprotected sex but just not this time, ok? So, here it comes 3 2 1... protected modifier! Yes, today we will talk about the protected modifier in Java. Yeah I know, you may have expected something else, like the things I mentioned before.
So let's go! At the beginning let me recap the default (package) modifier. To use this one we don't put anything in front of the member of a class, like in the following example:
 package example;
class DefaultAccess {
int a;
}

By this the member 'a' has the package access. That means that any other class in the package 'example' (or any other that we define) can access the member 'a' by a dot operator. And it's legal only in this package. A try to access it from any other package will not work. No exceptions. No excuses.

All right, that's pretty straightforward but this article is about the protected se... protected modifier it is! Okay. A protected modifier works in the same way as a default modifier as for the dot operator. So you can access a protected member within the same package with no problem. But outside it, you can forget. Well, nearly. You can actually make some sort of magic to access a protected member in the different package. And this magic is... inheritance! Okay, not a lot of magic in it. So, what we can do to access it, is to extend the class that has a protected member and then within its methods we can work around. Let's have a look at this example:
package protectedExample;

public class Loo {
protected int a;
}

package protectedExampleDifferent;

import protectedExample.Loo;

public class Woo extends Loo{
void callWoo() {
System.out.println(a);
}
}

That's how it works. First, we extend the class with protected member and then we can access it as in the normal inheritance. But how does it look for other classes that use the Woo class. Can they access the inherited member? The answer is no. For any other class, regardless to the package (of course excluding the one that the protected member is defined in) the protected inherited member is not visible. If we extend the previous example we can get:
package protectedExampleDifferent;

import protectedExample.Loo;

public class Woo extends Loo{
void callWoo() {
System.out.println(a);
}
}

class Woo2 {
void test() {
Woo woo = new Woo();
System.out.println(woo.a);
}
}
And here it's not gonna work. Even though the member 'a' is inherited and can be used within the Woo class, it can't be accessed by the dot operator by another class.
But this is not the end! We can still extend our class Woo and guess what! The member 'a' will be inherited! Let's slightly modify the previous example again:
package protectedExampleDifferent;

import protectedExample.Loo;

public class Woo extends Loo{
void callWoo() {
System.out.println(a);
}
}

class Woo2 extends Woo {
void test() {
System.out.println(a);
}
}

That's pretty savvy but that's how it works. How useful and powerful it can be!

Sunday, August 1, 2010

A few words about classpaths.

Perfect, so here we are - classpaths. The topic that nearly every programmer had a contact with but some have very shallow knowledge about them. That's why I'll recap this subject.
All right, so what actually are the classpaths? The classpaths are the directories that 'java' and 'javac' look inside, in order to find the classes that are necessary to proceed with current operations. A note: classpaths are not the only places where 'java' and 'javac' look in. Before the standard directories of JSE are searched through.

The syntax of it is as follows:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo

And now some important things:

In the above example, the Unix syntax was used as for the path directories. In the windows we will have to use something like C:\ (or other drive) and afterwards the backslashes (\).

The next thing worth mentioning is the order. The classpaths are searched from left to right so if the class that we are looking for is both in /com/foo/bar and /com/foo2/bar then we can get different results when using this two options:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo
-classpath /com/foo2/bar:/com/foo/bar:bar/foo

Ok, now we will talk about the current directory. You see, in both of the above examples the current directory is not searched! Yes, it's not searched for the .class files! I mean, if you simply invoke 'javac' with some .java file it's no problem. But as for the .class files it's just not searched. To change it, we have to add a current directory to the classpath which is denoted by a dot (.). Here is a modified previous example:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo:.

As simple as that! Never forget to add the . if the current directory has to be searched!

Also please note that there is a distinction between absolute and relative classpaths. Absolute classpath in Unix will start with a slash and doesn't matter the directory it is used from, the effect will always be the same. In case of relative classpath the effect won't be the same since the current directory is treated as a root directory for it, so if run from the wrong directory mostly the attempt will fail due to the fact that class can't be found.

The last thing that I would like to mention about the classpaths are the JAR files. In comparison to the the class files, we have to add a name of the JAR file that we want to use. So let's say that a my.JAR file is located in /com/foo/bar. To make the actual use of it we have to modify our previous example to:

 -classpath /com/foo/bar:/com/foo2/bar:bar/foo:.:/com/foo/bar/my.JAR

That's a bunch of useful information, isn't it? Yeah, stay tuned! There will be much more in the next articles!

Sunday, July 18, 2010

Threads part 2: functions overview.

All right, in the last article I already revealed that the thread can go to sleep. It can also do much more but for the good beginning we will start with this pleasant activity that many of us adore. Just a note: all of the methods presented in this article belong to java.lang.Thread class. Ok, cutting to the chase let's have a look at the definition:
 public static void sleep(long milliseconds) throws InterruptedException

So what actually does this method? It enables us to pause a thread for at least the time specified in the argument. Why at least? Because when the thread wakes up after specified time it goes into runnable state where it has to be chosen by the scheduler to run.
Now let's emphasize two important points about the sleep method. First of all it throws an exception so always remember to put it into the try-catch block or let the exception be handled up by declaring it.
The second thing is that the sleep method is static. So we can just invoke it like this:
 try {
Thread.sleep(1000);
catch(InterruptedException ie) {}

but also it's perfectly legal to use any instance of the thread class to do it, ie:
 Thread t = new Thread();
try {
t.sleep(1000);
catch(InterruptedException ie) {}

The thing to remember here is that it doesn't really matter on which instance of the Thread class we will invoke the sleep function. Always the thread that it is invoked from will be paused.

So far so good, right? Now it's time for another method:
 public static void yeld()

Now you probably bite your nails impatiently wondering what does it do. Ok you can stop nibbling, I will tell you. It moves the thread that it is invoked from into the runnable state. Now you probably ask a question why would one do it. This method is supposed to help the other threads with the same priority to get some time of the CPU. But it's not guaranteeded at all cause the scheduler can pick the same thread to execute. But still there is a chance that another thread will be chosen so the CPU will be utilized more fairly.

The next method I will describe today is join(). As before first goes the definition:
 public final void join() throws InterruptedException

And here goes the real magic. The method join makes the thread that it is invoked from, to wait for thread that the join() was invoked on, to finish. Yeah I know. I'll explain it using a very close example to many of us. Let's imagine a thread that is responsible for drinking vodka - its run method invokes a function drinkVodka(). But we don't want to finish drinking vodka and not to have any sort of chaser. So unless we are russians or college students we would like to have another thread that will bring chaser and what's more have it before we finish the vodka. So what we can do here is to invoke a join() method in the vodka thread on the reference to the bring-chaser thread. It will make the drinking-vodka thread to wait until the bring-chaser thread is finished.

And here is a real example, more mundane:
 public class MyThreadClass implements Runnable {
static int sum = 0;
public void run() {
try {
Thread.sleep(1000);
} catch(Exception e) {}
for(int i = 0; i < 100; i++) {
sum += 1;
}
}
public static void main(String[] args) throws Exception {
MyThreadClass r = new MyThreadClass();
Thread t = new Thread(r);
t.start();
System.out.println("Started!");
t.join();
System.out.println("The result is: " + sum);
}
}

What is happening here is that we run a new thread that waits a second and then do a simple addition. This thread is run from the main thread which waits until the calculating thread is done by invoking a join() method on it! For a simple exercise you can comment this line and see how the program behaves and what it prints.

And that's it for today! I hope you have had at least great time while reading it and that you already can't wait for another article! ;)

Threads part 1: The basics.

All right, today we will have a look at some really hot stuff - thread creation! This is basic but as many basics is very powerful.

First of all, how to to create a new thread? That's really easy actually. We have 2 ways to do it:

1. We can extend the java.lang.Thread class and override the run() method, like this:
 public class MyThreadClass extends Thread {
public void run() {
System.out.println("This is how we do it!");
}
}

2. We can implement the Runnable interface.
In the Runnable interface the only method that we are supposed to implement is public void run().
 public class MyThreadClass2 implements Runnable {
public void run() {
System.out.println("This is how we do it better!");
}
}

Ok, so far what we have is just a new defined class which has a great potential to be something bigger in our program. Let's instantiate our thread! For the first case that we just considered the only thing to do is:
 MyThreadClass myThreadClass = new MyThreadClass();
Duh...

The second case though will require all 2 lines of code! Here it is:
 MyThreadClass2 r = MyThreadClass2();
Thread t = new Thread(r);

And what we just did is firstly create a runnable object with implemented run() method and then pass it to the Thread class constructor so that our run() will be used when the thread goes into the live!

What we do next is starting a thread!
 t.start();

Nothing more, nothing less. Now we have a new thread alive but as in our lives a lot can happen meanwhile... like for example something that I'm going to do very soon - sleeping. But about this and more I will write in the next part of the article.

Friday, July 16, 2010

Synchronization - static and non-static methods.

The interesting thing about the synchronization is when we deal with both static and non-static methods of a class. Actually, interesting and hazardous as well.

Let's consider such a case. We have a class, that has a field which can be both accessed from a static synchronized method and another, non-static synchronized method. Both of them are synchronized so everything should be fine. But it is not. This example illustrates our problem:

 public class MyClass implements Runnable {  
private static int a = 5;
public synchronized static void play() {
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " work with " + a + " and is counting: " + i);
try {
Thread.sleep(1);
} catch(Exception e) {}
}
}
public synchronized void play2() {
for(int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " work with " + a + " and is counting: " + i);
}
}
public void run() {
if(Thread.currentThread().getName().equals("first")) {
play();
}
else {
play2();
}
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
Thread first = new Thread(myClass);
Thread second = new Thread(myClass);
first.setName("first");
second.setName("second");
first.start();
second.start();
}
}


And the possible output that we can get is as follows (it will vary anytime you run the code):


first work with 5 and is counting: 0
first work with 5 and is counting: 1
second work with 5 and is counting: 0
second work with 5 and is counting: 1
first work with 5 and is counting: 2
second work with 5 and is counting: 2
second work with 5 and is counting: 3
second work with 5 and is counting: 4
second work with 5 and is counting: 5
first work with 5 and is counting: 3
second work with 5 and is counting: 6
second work with 5 and is counting: 7
second work with 5 and is counting: 8
first work with 5 and is counting: 4
second work with 5 and is counting: 9
first work with 5 and is counting: 5
first work with 5 and is counting: 6
first work with 5 and is counting: 7
first work with 5 and is counting: 8
first work with 5 and is counting: 9


And as I said before it's not fine. The operations of counting are interfering each other like in case of no synchronization. The problem is due to the different locks that are acquired by the non-static and static methods. The static methods acquire the lock belonging to this in contrary to the non-static methods which acquire the lock of java.lang.Class that every loaded class has.

So during your programming voyages be careful to this!

Friday, July 2, 2010

The start!

Welcome to my Software Engineering blog!

Thank you for visiting it and I hope you will spend here very good time. In this first article I will write about the areas that the blog will cover. First of all, it's going to be about IT. So it can be about... yeah pretty a lot of stuff actually! Though to be more precise, I can reveal that at the beginning it will be more Java focused as currently I'm preparing myself for an exam to become Sun Certified Java Programmer. So I'll post here some tricky parts about the Java language that I have had occasion to learn during my preparation. Besides this, I'll bring up the topics of Design Patterns, Object Oriented best practices, Jave EE and much more! I will focus on the features that are the most up to date and can be useful and helpful for many of you!

And now is the time for a video! What would you do in a place of this young teenager facing a problem of such horrible incomprehension from his parents?