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?