My Technology blog…

Juicy Java Tidbits picked up from everywhere

Archive for the ‘Uncategorized’ Category

An Aside : A useful database question…

Posted by tanvis on August 30, 2007

Delete Duplicate Rows From an Oracle Table

An easy way to remove the duplicate rows before the primary key or unique indexes can be created:


DELETE FROM table_name
WHERE rowid not in
(SELECT MIN(rowid)
FROM table_name
GROUP BY column1, column2, column3... ;

The GROUP BY is used on the columns that make the primary key for the table. This query deletes each row in the group after the first row.

Posted in Database, Database Delete, SQL, Uncategorized | Leave a Comment »

Java Sizeof()

Posted by tanvis on August 11, 2007

Java of course doesnt have a sizeof method for objects. So then how do we measure the size of a Java object in the system?

Method 1: Serialize the object and measure the size of the byte stream.
Problem: But that would not work because objects are not the same size when they are resident in the JVM and when they are serialized. The way the objects are encoded changes the actual size of the object.
Example: Strings. Every character is two bytes in memory and lesser than that when the object is encoded using the UTF-8 encoding format before serialization.

Method 2:
Create a large number of identical class instances and carefully measure the resulting increase in the JVM used heap size.

Method 3: An object instance can be (approximately) sized by totaling all of its non-static data fields (remember to include fields defined in the superclass). Class super interfaces have no impact on the  object size. the full object size can be obtained as a closure over the entire object graph rooted at the starting object.

// java.lang.Object shell size in bytes:
    public static final int OBJECT_SHELL_SIZE   = 8;
    public static final int OBJREF_SIZE         = 4;
    public static final int LONG_FIELD_SIZE     = 8;
    public static final int INT_FIELD_SIZE      = 4;
    public static final int SHORT_FIELD_SIZE    = 2;
    public static final int CHAR_FIELD_SIZE     = 2;
    public static final int BYTE_FIELD_SIZE     = 1;
    public static final int BOOLEAN_FIELD_SIZE  = 1;
    public static final int DOUBLE_FIELD_SIZE   = 8;
    public static final int FLOAT_FIELD_SIZE    = 4;

Posted in Uncategorized | Leave a Comment »

Threads – Interrupts

Posted by tanvis on August 1, 2007

Interrupts

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It’s up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. This is the usage emphasized in this lesson.A thread sends an interrupt by invoking interrupt on the Thread object for the thread to be interrupted. For the interrupt mechanism to work correctly, the interrupted thread must support its own interruption.

Supporting Interruption

How does a thread support its own interruption? This depends on what it’s currently doing. If the thread is frequently invoking methods that throw InterruptedException, it simply returns from the run method after it catches that exception. For example, suppose the central message loop in the SleepMessages example were in the run method of a thread’s Runnable object. Then it might be modified as follows to support interrupts:

for (int i = 0; i < importantInfo.length; i++) {
//Pause for 4 seconds
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
//We’ve been interrupted: no more messages.
return;
}
//Print a message
System.out.println(importantInfo[i]);
}

Many methods that throw InterruptedException, such as sleep, are designed to cancel their current operation and return immediately when an interrupt is received.

What if a thread goes a long time without invoking a method that throws InterruptedException? Then it must periodically invoke Thread.interrupted, which returns true if an interrupt has been received. For example:

for (int i = 0; i < inputs.length; i++) {
heavyCrunch(inputs[i]);
if (Thread.interrupted()) {
//We’ve been interrupted: no more crunching.
return;
}
}

In this simple example, the code simply tests for the interrupt and exits the thread if one has been received. In more complex applications, it might make more sense to throw an InterruptedException:

if (Thread.interrupted()) {
throw new InterruptedException();
}

This allows interrupt handling code to be centralized in a catch clause.

The Interrupt Status Flag

The interrupt mechanism is implemented using an internal flag known as the interrupt status. Invoking Thread.interrupt sets this flag. When a thread checks for an interrupt by invoking the static method Thread.interrupted, interrupt status is cleared. The non-static Thread.isInterrupted, which is used by one thread to query the interrupt status of another, does not change the interrupt status flag.

By convention, any method that exits by throwing an InterruptedException clears interrupt status when it does so. However, it’s always possible that interrupt status will immediately be set again, by another thread invoking interrupt.

Joins

The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,

        t.join();

causes the current thread to pause execution until t’s thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.

 Like sleep, join responds to an interrupt by exiting with an InterruptedException.

Finally, an example:

The SimpleThreads Example

    The following example brings together some of the concepts of this section. SimpleThreads consists of two threads. The first is the main thread that every Java application has. The main thread creates a new thread from the Runnable object, MessageLoop, and waits for it to finish. If the MessageLoop thread takes too long to finish, the main thread interrupts it.
    The MessageLoop thread prints out a series of messages. If interrupted before it has printed all its messages, the MessageLoop thread prints a message and exits.

        public class SimpleThreads {

            //Display a message, preceded by the name of the current thread
            static void threadMessage(String message) {
                String threadName = Thread.currentThread().getName();
                System.out.format(“%s: %s%n”, threadName, message);
            }

            private static class MessageLoop implements Runnable {
                public void run() {
                    String importantInfo[] = {
                        “Mares eat oats”,
                        “Does eat oats”,
                        “Little lambs eat ivy”,
                        “A kid will eat ivy too”
                    };
                    try {
                        for (int i = 0; i < importantInfo.length; i++) {
                            //Pause for 4 seconds
                            Thread.sleep(4000);
                            //Print a message
                            threadMessage(importantInfo[i]);
                        }
                    } catch (InterruptedException e) {
                        threadMessage(“I wasn’t done!”);
                    }
                }
            }

            public static void main(String args[]) throws InterruptedException {

                //Delay, in milliseconds before we interrupt MessageLoop
                //thread (default one hour).
 
               long patience = 1000 * 60 * 60;

                //If command line argument present, gives patience in seconds.
 
               if (args.length > 0) {
                    try {
                        patience = Long.parseLong(args[0]) * 1000;
                    } catch (NumberFormatException e) {
                        System.err.println(“Argument must be an integer.”);
                        System.exit(1);
                    }

                }

                threadMessage(“Starting MessageLoop thread”);
                long startTime = System.currentTimeMillis();
                Thread t = new Thread(new MessageLoop());
                t.start();

                threadMessage(“Waiting for MessageLoop thread to finish”);

                //loop until MessageLoop thread exits
                while (t.isAlive()) {
                    threadMessage(“Still waiting…”);
                    //Wait maximum of 1 second for MessageLoop thread to
                    //finish.

                    t.join(1000);
                    if (((System.currentTimeMillis() – startTime) > patience) &&
                            t.isAlive()) {
                        threadMessage(“Tired of waiting!”);
                        t.interrupt();
                        //Shouldn’t be long now — wait indefinitely
                        t.join();
                    }

                }
                threadMessage(“Finally!”);
            }
        }

Posted in Java Multi-threading, Java Threads, Threads, Uncategorized | Leave a Comment »

Thread Basics

Posted by tanvis on August 1, 2007

An application that creates an instance of Thread must provide the code that will run in that thread. There are two ways to do this:

  • Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread. The Runnable object is passed to the Thread constructor, as in the HelloRunnable example:

             public class HelloRunnable implements Runnable
             {
                    public void run() {   
                            System.out.println(“Hello from a thread!”);
                    }
                    public static void main(String args[]) {
                            (new Thread(new HelloRunnable())).start();
                    }
              }

  • Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing. An application can subclass Thread, providing its own implementation of run, as in the HelloThread example.

    public class HelloThread extends Thread

             {
                    public void run() {
                             System.out.println(“Hello from a thread!”);
                    }
                    public static void main(String args[]) {
                             (new HelloThread()).start();
                    }
             }

Notice that both examples invoke Thread.start in order to start the new thread.The first idiom, which employs a Runnable object, is more general, because the Runnable object can subclass a class other than Thread. The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread. We focus on the first approach, which separates the Runnable task from the Thread object that executes the task. Not only is this approach more flexible, but it is applicable to the high-level thread management APIs.The Thread class defines a number of methods useful for thread management. These include static methods, which provide information about, or affect the status of, the thread invoking the method. The other methods are invoked from other threads involved in managing the thread and Thread object.

Something to remember:

In Java, every thread begins by executing a run() method in a particular object. Run() is declared to be public, takes no arguments, has no return value, and is not allowed to throw any exceptions. Any class can implement a run() method by declaring that the class implements the Runnable interface.

 

Thread.sleep

sleep

public static void sleep(long millis) throws InterruptedException

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds. The thread does not lose ownership of any monitors.
Parameters:
millis – the length of time to sleep in milliseconds.
Throws:

InterruptedException- if another thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreads example in a later section.

Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we’ll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.

The SleepMessages example uses sleep to print messages at four-second intervals:

public class SleepMessages {

public static void main(String args[]) throws InterruptedException
{

        String importantInfo[] = {
                            “Mares eat oats”,
                            “Does eat oats”,
                            “Little lambs eat ivy”,
                            “A kid will eat ivy too”
        };
       
        for (int i = 0; i < importantInfo.length; i++)
        {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}

Notice that main declares that it throws InterruptedException. This is an exception that sleep throws when another thread interrupts the current thread while sleep is active. Since this application has not defined another thread to cause the interrupt, it doesn’t bother to catch InterruptedException.

 

Posted in Threads, Uncategorized | 1 Comment »

Collections trivia – Unmodifiable Collections

Posted by tanvis on July 10, 2007

Unmodifiable Collections can be easily created using various static methods which the Collections class provides. Any attempts to modify the returned Collection, whether direct or via its iterator, result in an UnsupportedOperationException.

Collection<T> unmodifiableCollection(Collection<? extends T> c)

List<T> unmodifiableList(List<? extends T> list)

Set<T> unmodifiableSet(Set<? extends T> s)

SortedSet<T> unmodifiableSortedSet(SortedSet<T> s)
import java.util.*;
public class Unmod{

public static void main(String[] args){

List<String> strlist = new ArrayList<String>();

strlist.add(“C”);

strlist.add(“B”);

strlist.add(“A”);

Collection<String> unmodstrlist = Unmod.makeUnmodifiable(strlist);

// unmodstrlist.add(“G”); throws UnsupportedOperationException
Set<String> strset = new TreeSet<String>();

strset.add(“C”);

strset.add(“B”);

strset.add(“A”);

Collection<String> unmodstrset = Unmod.makeUnmodifiable(strset);

// unmodstrset.add(“G”); throws UnsupportedOperationException

}
public static Collection<String> makeUnmodifiable(Collection<String> c){

return(Collections.unmodifiableCollection(c));

}

}

Posted in Uncategorized | Leave a Comment »

Collections trivia

Posted by tanvis on July 10, 2007

How would you preserve the order of insertion of entries into a Map?public class LinkedHashMap
extends HashMap

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashMap (and Hashtable), without incurring the increased cost associated with TreeMap. It can be used to produce a copy of a map that has the same order as the original, regardless of the original map’s implementation:

void foo(Map m) {
Map copy = new LinkedHashMap(m);

}
This technique is particularly useful if a module takes a map on input, copies it, and later returns results whose order is determined by that of the copy. (Clients generally appreciate having things returned in the same order they were presented.)

A special constructor is provided to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order). This kind of map is well-suited to building LRU caches. Invoking the put or get method results in an access to the corresponding entry (assuming it exists after the invocation completes). The putAll method generates one entry access for each mapping in the specified map, in the order that key-value mappings are provided by the specified map’s entry set iterator. No other methods generate entry accesses. In particular, operations on collection-views do not affect the order of iteration of the backing map.

The removeEldestEntry(Map.Entry) method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.

This class provides all of the optional Map operations, and permits null elements. Like HashMap, it provides constant-time performance for the basic operations (add, contains and remove), assuming the the hash function disperses elements properly among the buckets. Performance is likely to be just slightly below that of HashMap, due to the added expense of maintaining the linked list, with one exception: Iteration over the collection-views of a LinkedHashMap requires time proportional to the size of the map, regardless of its capacity. Iteration over a HashMap is likely to be more expensive, requiring time proportional to its capacity.

A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.

Note that this implementation is not synchronized. If multiple threads access a linked hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be “wrapped” using the Collections.synchronizedMapmethod. This is best done at creation time, to prevent accidental unsynchronized access:

Map m = Collections.synchronizedMap(new LinkedHashMap(…));
A structural modification is any operation that adds or deletes one or more mappings or, in the case of access-ordered linked hash maps, affects iteration order. In insertion-ordered linked hash maps, merely changing the value associated with a key that is already contained in the map is not a structural modification. In access-ordered linked hash maps, merely querying the map with get is a structural modification.)

The iterators returned by the iterator methods of the collections returned by all of this class’s collection view methods are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the Iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Posted in Collections, Java Collections, Uncategorized | Leave a Comment »