Posts tagged ‘java’

Half a half: Part 2

Ten days ago we had a look at Java’s ability to deal with numbers which had alot of decimal places. Liam pointed out that having to loop through a variety of operations is longer than performing a more efficient operation once.

With Liams magical formula, we get the following Java, with no loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.math.BigDecimal;
 
public class The_proper_half {
 
    public static Integer times_to_loop;
 
    /**
     * @param args the number of times you want to run the loop
     */
    public static void main(String[] args) {
        calculate(Integer.valueOf(args[0]));
 
    }
 
    public static void calculate(int times_to_loop) {
        //The Number we want to half
        BigDecimal number_to_half = new BigDecimal("10");
        //The result of doing the half
        BigDecimal the_half = new BigDecimal("0");
        //The number we want to divide by
        BigDecimal divider = new BigDecimal("2");
 
        the_half = (number_to_half.divide(divider.pow(times_to_loop)));
 
        System.out.println("The last number has " +
                ((Integer) number_to_half.subtract(the_half).toString().length()
                - 2) + " decimal places: ");
 
        System.out.println(number_to_half.subtract(the_half));
    }
}

As you can see, we only perform the opertation once (line 23), but admitadly, to get the correct number at the end, we still do the subtraction at the end!

Regarding optimisation, there are huge benefits. It turns out that the old way if hugely costly for thousands of iterations. These are the results for 10000 iterations, the old way:

anton@anton-laptop classes $ time java Half_of_a_half 10000 > /dev/null

real    5m22.714s
user    5m21.320s
sys    0m1.052s

The results for the new way are much better:

anton@anton-laptop classes $ time java The_proper_half 10000 > /dev/null

real    0m1.019s
user    0m1.248s
sys    0m0.052s

So it went from over five minutes, down to just a second. That was just by changing from a loop a single statement. Thats pretty cool stuff!

I have to admit here, the difficult bit is probably not the code. Its the abillity to see how a problem may be translated from one way of expressing it to another. Its that bit of genius thats really done the work here. Credit to Liam for the genius!

Half a number, half it again and add it to the first half.

This is a common riddle, so if you’ve heard it, don’t shout out the answer (people might think your strange for shouting at the internet….)

Take a number. Then, half that number. Then half that half and add it to the first half. Before that gives people a headache, lets do a little example:

Lets use 10 . Then half of ten gives us 5. Then, half five (2.5) and add it to the first half, 5. This gives us 7.5

Continue to half the last half, adding it to the sum of the previous halves. Phew, I hope thats explained properly.i.e. half two point five, and add it the the 7.5 we already have, which give us 8.25

Okay, so the question is this. If we keeping adding on the halves, will we ever reach 10 again? Well, I like Java, so lets get all geeky and model the problem. For this, the double and float data types won’t give us enough decimal places. For this, we’ll need: math.BigDecimal . The Big Decimal. Sounds ominous!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import java.math.BigDecimal;
public class Half_of_a_half {
 
    public static Integer times_to_loop;
 
    /**
     * @param args the number of times you want to run the loop
     */
    public static void main(String[] args) {
        calculate(Integer.valueOf(args[0]));
    }
 
    public static void calculate(int times_to_loop) {
        //The Number we want to half
        BigDecimal number_to_half = new BigDecimal("10");
        //The result of doing the half
        BigDecimal the_half = new BigDecimal("0");
        //The number we want to divide by
        BigDecimal divider = new BigDecimal("2");
 
        for (int i = 0; i < times_to_loop; i++) {
 
            number_to_half = number_to_half.divide(divider);
            the_half = the_half.add(number_to_half);
 
            System.out.println(the_half);
        }
        System.out.println("The last number has " +
                ((Integer) the_half.toString().length() - 2) + " decimal places");
    }
}

This code takes a single parameter on the command line: the number of times to half by

e.g.

anton@anton-laptop classes $ java Half_of_a_half 10
5
7.5
8.75
9.375
9.6875
9.84375
9.921875
9.9609375
9.98046875
9.990234375
The last number has 9 decimal places

So as we can see, the decimal places just get long and longer. The additions are never big enough to get us close enough to the original number. Problem solved!

The fun bit is realising the significance of the calculation, or rather, the speed with which it was done. Performing 1000 divisions and additions takes less that 0.2 of a second! Maybe thats not so fast by todays computing ability, but by human standards thats pretty extreme.

anton@anton-laptop classes $ time java Half_of_a_half 1000 > /dev/null


real    0m1.387s
user    0m1.916s
sys    0m0.036s

Using synchronized methods in java

This post has long code segments in it, so I’ll explain what it all does at the top. Then at the end, just copy paste into your favourite editor/IDE to play with it.

So the title kind of gives it away, but the concept behind it was quite interesting. Imagine you have some kind of resource, like a network connection, a file etc, which is needs to be accessed by many threads, but only one thread at a time. Using synchronized methods achieves this. Its especially handy where you might have hundreds of threads which need to modify the same resource, but should do it, one at a time. This code can do that (although its not perfect by far)

In this example, we have a padlock, which we can open , and close. Of course, we can’t open it whilst its being closed, and vica versa. You could just run the openLock and closeLock methods one after the other, but using threads gives us some bonus features. For example, we might want to open the padlock, get half way through, and then realise we want to pause, leaving the rest of the work for later. Or maybe we want to get halfway through closing the padlock, and then change our mind and open it (i.e. without fully closing it)

So heres the code, enjoy!
The padlock:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package workingWithSynchronizedThreads;
 
import java.util.logging.Level;
import java.util.logging.Logger;
 
/**
 * This class represents a simple padlock. You know, like the kind you use to
 * lock up your bike. I use it as an example of how we can make fields in
 * java , then try and access them through different threads. Using syncronised
 * methods, we will prevent the lock from being opened whilst were still trying
 * to close it.
 * @author anton
 */
public class padlock {
 
    /**
     * Constructor object to make a new padlock
     * @param isThePadlockOpen Whether the padlock is open or closed
     */
    public padlock(boolean isThePadlockOpen) {
        this.isThePadlockOpen = isThePadlockOpen;
    }
    /**
     * This field tells us whether or not the lock is open or closed (true for
     * open, false for locked)
     */
    public boolean isThePadlockOpen;
 
    /**
     * This method simply sets the padlock to be closed by setting isOpen to false
     * Closing the lock takes two seconds (hence the sleep statements) ).
     */
    public synchronized void closeLock() {
        try {
            Thread.sleep(1000);
            isThePadlockOpen = false;
            System.out.println("I'm closing the lock");
            Thread.sleep(1000);
            tellMeIfThisLockIsOpen();
        } catch (InterruptedException ex) {
            System.out.println("I couldn't close the lock");
            Logger.getLogger(padlock.class.getName()).log(Level.SEVERE, null, ex);
        }
 
    }
 
    /**
     * This method simply sets the padlock to be open by setting isOpen to true.
     * Opening a lock takes two seconds (hence the sleep statements ).
     */
    public synchronized void openLock() {
        try {
            Thread.sleep(1000);
            isThePadlockOpen = true;
            System.out.println("I'm opening the lock");
            Thread.sleep(1000);
            tellMeIfThisLockIsOpen();
        } catch (InterruptedException ex) {
            System.out.println("I couldn't open the lock");
            Logger.getLogger(padlock.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
    /**
     * Lets us know if our padlock object is open or closed
     */
    public void tellMeIfThisLockIsOpen() {
        if (isThePadlockOpen == true) {
            System.out.println("The lock is open!");
        } else if (isThePadlockOpen == false) {
            System.out.println("The lock is closed!");
        } else {
            System.out.println("Something is seriously wrong!");
        }
    }
}

The closeLockThread:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package workingWithSynchronizedThreads;
 
/**
 *
 * @author anton
 */
public class closeLockThread extends Thread {
 
    public padlock padlock;
 
    public closeLockThread(Object padlock) {
        this.padlock = (padlock) padlock;
    }
 
    @Override
    public void run() {
        padlock.closeLock();
    }
}

The openLockThread:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package workingWithSynchronizedThreads;
 
/**
 *
 * @author anton
 */
public class openLockThread extends Thread {
 
    public padlock padlock;
 
    public openLockThread(Object padlock) {
        this.padlock = (padlock) padlock;
    }
 
    @Override
    public void run() {
        padlock.openLock();
 
    }
}

Okay, less mess with some threads!!!:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package workingWithSynchronizedThreads;
 
/**
 *
 * @author anton
 */
public class messAroundWithSomePadlocks {
 
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        padlock myLock = new padlock(true);
        closeLockThread iWannaCloseTheLock = new closeLockThread(myLock);
        openLockThread iWannaOpenTheLock = new openLockThread(myLock);
        iWannaCloseTheLock.start();
        iWannaOpenTheLock.start();
    }
}

The things that need attention are:

  1. Do we need to do that casting from padlock to padlock in the openLock and closeLock thread classes?
  2. Is it ok/understandable to make a field a question? (public boolean isThePadlockOpen;) ?

The inspiration for this work came from looking at some code were working on in my department, but the learning was really done looking at the Java Tutorials, which are ace!

a new kind of extreme programming

XP is regarded as a good technique for producing clean effective code. I however think that pulling yet another all nighter is also extreme. I guess the logical conclusion would be to code with a laptop whilst skydiving from a plane……a bit like extreme ironing

Once this coursework is handed in, my house mate Darren will have been  awake, coding, for 51 hours including doing a  part time job. 51 hours!!!!! Thats got to be the new definition of XP!

The upside is that in that time, I managed to implement SMTP in a Java using sockets. nice.

A word of warning: eating chicken korma during a code marathon is likely to knock you out for two hours……

Netbeans 6.0 rc2 – What a joy to use!

This post is for the benefit of anyone who had the displeasure of using Netbeans 5.0 that came with OpenSuse 10.3 .

The first thing to say is that netbeans does take a little while to load, which is a shame really because it looks like they missed the opportunity to show off javas threading abilities. The other downer is that it eats alot of ram :( you’ll want at least a gig to run netbeans and happily get on with your other desktop tasks (music, word processing etc)

After the load, the fun stuff!

The best thing to say is that the web container integration works really well. It comes with glassfish as a standard, but you can add many different different verions of tomcat ontop if you prefer that. It makes deploying your servlets or jsps as easy as hiting F6 (which runs you main project, remember to select your project as main first!) . You can change where netbeans deploys the servlet by right clicking on the project and going to properties. Once in properties you can go down to run and select your server :) Of course, you will need to have the server running first!

IMO the best update for the editor is the code highlighting, particularly the instant rename. You can basically out the caret in the middle of a word and hit <ctrl> + R The editor then selects every other instance of that word in the file and changes it as you change the currently selected one accordingly.