Wednesday, June 9, 2010

Initialization of list/map in one line

List
ArrayList places = new ArrayList(Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

ArrayList list = new ArrayList() {{
add("A");
add("B");
add("C");
}}

link

Map
Map m = new HashMap() {
{
put(".jpg", "image/jpeg");
put(".jpeg", "image/jpeg");
}
};

Sunday, April 11, 2010

Java Concurrency/Threads

Process vs Thread
Process - is a running program that runs independently from other processes. It has its own address space and cannot directly access resources of other processes. Each process can have one or more threads.

Thread - is sometimes called lightweight process. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads share the process's resources, including memory and open files.

2 ways to define a Thread:
  1. implement Runnable interface
    - more general, can have many superclass
    - starting: (new Thread(new HelloRunnable())).start();
  2. extend Thread class (Thread class itself implements Runnable)
    - simpler but limited
    - starting: (new HelloThread()).start();

Thread methods:
  • public void run() - the only method coming from Runnable
  • public void start() - calls the run() method, can only be called once
  • public static void sleep(long millis)/(long millis, int nanos) throws InterruptedException - suspend execution for a specified period
    - time is not guaranteed
    - can be interrupted
  • public void interrupt() - indicates that thread should stop
  • public static boolean interrupted() - interrupted status is cleared
  • public boolean isInterrupted() - has no effect on interrupted status
  • public final void stop()/suspend()/resume() - deprecated

ObjectThread
notify
notifyAll
wait
sleep
yield


Source: http://java.sun.com/docs/books/tutorial/essential/index.html
http://www.vogella.de/articles/JavaConcurrency/article.html

Thursday, April 1, 2010

Using Resource Bundle

ResourceBundle is a class used for containing locale-specific data. A Locale defines the user's environment particularly its language and region. A certain number in one locale may be written differently in another. Likewise, a label of a "Cancel" button may differ in different locales. Using ResourceBundle will allow you to handle these different locales without having to hard-code the locale-specific data.

Sample of retrieving locale-specific data
list of resource bundles:
ButtonLabel
ButtonLabel_de
ButtonLabel_en_GB
ButtonLabel_fr_CA_UNIX


selecting the locale-specific ButtonLabel resource bundle:
Locale currentLocale = new Locale("fr", "CA", "UNIX");
ResourceBundle introLabels =
ResourceBundle.getBundle("ButtonLabel", currentLocale);


2 Types of ResourceBundle
  1. PropertyResourceBundle - uses a properties file to contain the key-value pairs. The value can only be a String.

    properties files for 3 resource bundles:
    LabelsBundle.properties
    LabelsBundle_de.properties
    LabelsBundle_fr.properties

    resource bundle sample content:
    # This is the LabelsBundle_de.properties file
    s1 = Computer
    s2 = Platte
    s3 = Monitor
    s4 = Tastatur

    use of resource bundle sample:
    Locale[] supportedLocales = {
    Locale.FRENCH,
    Locale.GERMAN,
    Locale.ENGLISH
    };

    for (int i = 0; i < supportedLocales.length; i ++) {
    ResourceBundle labels =
    ResourceBundle.getBundle("LabelsBundle",currentLocale);

    String value = labels.getString(key);
    Enumeration bundleKeys = labels.getKeys();
    while (bundleKeys.hasMoreElements()) {
    String key = (String)bundleKeys.nextElement();
    String value = labels.getString(key);
    }
    }

  2. ListResourceBundle - uses a list to contain the key-value pairs. The value can be any object.

    3 resource bundles:
    StatsBundle_en_CA.class
    StatsBundle_fr_FR.class
    StatsBundle_ja_JP.class

    resource bundle sample:
    import java.util.*;
    public class StatsBundle_ja_JP extends ListResourceBundle {
    public Object[][] getContents() {
    return contents;
    }
    private Object[][] contents = {
    { "GDP", new Integer(21300) },
    { "Population", new Integer(125449703) },
    { "Literacy", new Double(0.99) },
    };
    }

    use of resource bundle sample:
    Locale[] supportedLocales = {
    new Locale("en","CA"),
    new Locale("ja","JP"),
    new Locale("fr","FR")
    };

    for (int i = 0; i < supportedLocales.length; i ++) {
    ResourceBundle stats =
    ResourceBundle.getBundle("StatsBundle",currentLocale);

    Integer gdp = (Integer)stats.getObject("GDP");
    }

Notes:
- things to check/consider when internationalizing: http://java.sun.com/docs/books/tutorial/i18n/intro/checklist.html
- numbers, dates, times, or currencies need not be isolated in a ResourceBundle because only the display format of these objects varies with Locale, the objects themselves do not
- it is better to have multiple ResourceBundle by determining related objects and grouping them together
- ResourceBundle.Control class provides a way to control the instantiation and location of resource bundles. You can override its methods to behave differently.
- list of language codes (ISO-639): http://ftp.ics.uci.edu/pub/ietf/http/related/iso639.txt
- list of country codes (ISO-3166): http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html

Source: http://java.sun.com/docs/books/tutorial/i18n/resbundle/index.html

Tuesday, March 23, 2010

Java Exceptions

Exception Objects
Throwable
'-> Error
'-> AnnotationFormatError
'-> AssertionError
'-> IOError
'-> ThreadDeath
'-> ...
'-> Exception
'-> RuntimeException
'-> ArithmeticException
'-> ArrayStoreException
'-> ClassCastException
'-> ConcurrentModificationException
'-> IndexOutOfBoundsException
'-> NullPointerException
'-> ...
'-> ClassNotFoundException
'-> CloneNotSupportedException
'-> InterruptedException
'-> IOException
'-> NoSuchMethodException
'-> ...

Kinds of Exceptions
  1. checked - all exceptions that are not RuntimeException
  2. unchecked
    - Error
    - RuntimeException


Notes
- finally is always executed even if there is a change of control flow like when there is a return statement in try
- can you catch runtime exception? yes, you can catch any Throwable type but since the cost of checking for runtime exceptions exceeds the benefit of catching or specifying them, the compiler does not require that you catch them
- for readable code, it's good practice to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class
- what to use when creating your own exception: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Ref: http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

Synchronized & Unsynchronized Objects

SynchronizedUnsynchronized
StringBufferStringBuilder
VectorArrayList
HashtableHashMap

Monday, March 22, 2010

Setting the CLASSPATH Sys Var

To display the current CLASSPATH variable, use these commands in Windows and Unix (Bourne shell):
In Windows:   C:\> set CLASSPATH
In Unix: % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use these commands:
In Windows:   C:\> set CLASSPATH=
In Unix: % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable, use these commands (for example):
In Windows:   C:\> set CLASSPATH=C:\users\george\java\classes
In Unix: % CLASSPATH=/home/george/java/classes; export CLASSPATH

From: http://java.sun.com/docs/books/tutorial/java/package/managingfiles.html

Tuesday, March 16, 2010

Declaring Constants

I was contemplating for the best way to declare constants in Java and found that there are several ways to do it. The best article I saw regading this topic is here. It helped me decide clearly as to what I should use plus, one of the comments discussed a very interesting information about inlining constants w/c I will also explain later on this blog.

First, I would like to eradicate suggestions/questions that might come up:

Why not use enums? I am referring here to constants that are not related and may even be of different types so enum is not a good choice.

If these constants are not related, why bother grouping them? This is sometimes necessary because there are constants that belong to the same functionality but are not related to each other. You may also want to group constants shared by different classes, more like global constants. These constants do not belong naturally to a certain class so it needs to be grouped somewhere else.

Why not put constants in the class that they are most related to? Aside from the explanation above, this would also lead to dependencies between classes and the constants will clutter. It's always easier to update just one class or few classes.

So what are the options now?

Interface for Constants
ADV:
- cleaner/shorter code because you can define constants without the public static final keywords since they are implicitly public static final
- a class implementing this can refer to the constants without a qualifying class name
DISADV:
- this is not what interface is designed for. Interface is supposed to specify a contract for its services, not to handle data.
- using constant without a qualifying class name can make code more difficult to understand and maintain
- interfaces promotes constants to the API of the class which means that if MyClass implements MyConstantInterface, you can use MyClass.SAMPLE_CONSTANT instead of MyConstantInterface.SAMPLE_CONSTANT. This breaks inheritance and your Javadoc will be full of repeating constants.

Class for Constants with private constructor
ADV:
- cannot be instantiated and cannot be subclassed like interfaces
- the use of qualifying name can add to the readability of the code
DISADV:
- long name, constants are referred using static references like MyConstantClass.SAMPLE_CONSTANT

static import
ADV:
- allow referring to constants without a qualifying class name
DISADV:
- can make code more difficult to understand and maintain

MY CONCLUSION:
You may choose one over another depending on what you need or what is more convenient for you, but for me the best approach is to use class with private constructor. This will avoid all the disadvantages of using an interface. If you still want to use interfaces because of the shorter name reference for constants, you must use static import of a constant class instead. However, this must be taken with precaution. Use it only if you need frequent access of constants from one or very few classes only. Otherwise, readers of your code may get confused as to where a constant comes from.

Now, is there anything else that can do better? Apparently, according to Kevin Riff, there is. When a field is (1)of type primitive or String, (2)declared final, and (3)was initialized upon declaration, it is called "compile-time constant" and it is in-lined in the consumer classes. This means that all reference of this constant is replaced with its actual value at compile time. So if you change the value of a constant, you must recompile not only the containing class but all its consumer classes in order to update the value of the constant.

What is the solution for this? Using a properties file could be considered but if you really need to hard-code your constants in a Java file, you must prevent your constants to be in-line like this,
public class MyLibrary { 
public static final String VERSION; // blank final
static {
VERSION = "1.0"; // initialized separately
}
}

The code would seem odd so don't forget to add comments explaining what's going on.

Personally, I might not apply this design because it makes the code look odd and somehow ugly. I would rather recompile all affected classes. It happens to almost any class anyway that when you make a change on it, there will be some affected classes that must be recompiled too.