java

Cloning Java Objects

Objects in Java are referred using reference types, and there is no direct way to copy the contents of an object into a new object. The assignment of one reference to another merely creates another reference to the same object. Therefore, a special clone() method exists for all reference types in order to provide a standard mechanism for an object to make a copy of itself. Here are the details you need to know about cloning Java objects.

Why create a local copy?

The most probable reason for creating a local copy of an object is because you plan to modify the object, and you don’t want to modify the method caller’s object. If you decide that you need a local copy, you can perform the operation by using the clone() method of the Object class. The clone() method is defined as protected, but you must redefine it as public in all subclasses that you might want to clone.

For example, the standard library class ArrayList overrides clone(), so you can call clone() for ArrayList, like this:



import java.util.*;class MyInt {

    private int i;

    public MyInt(int ii) { i = ii; }

    public void increment() { i++; }

    public String toString() {

        return Integer.toString(i);

    }

}

public class Test {

    public static void main(String[] args) {

        ArrayList al = new ArrayList();

        for(int i = 0; i < 10; i++ )

            al.add(new MyInt(i));

        ArrayList al1 = (ArrayList)al.clone();

        // Increment all al1's elements:

        for(Iterator e = al1.iterator(); e.hasNext(); )

            ((MyInt)e.next()).increment();

    }

}

The clone() method produces an Object, which must be recast to the proper type. This example shows how ArrayList’s clone() method does not automatically try to clone each of the objects that the ArrayList contains — the old ArrayList and the cloned ArrayList are aliased to the same objects. This is often called a shallow copy, since it’s only copying the “surface” portion of an object. The actual object consists of this “surface,” plus all the objects that the references are pointing to and all the objects those objects are pointing to, etc. This is often referred to as the “Web of objects.” When you copy the entire mess, it is called a deep copy.

The Cloneable interface and deep copies

By default, classes in Java do not support cloning; the default implementation of the clone() method throws a CloneNotSupportedException. You should override implementation of the clone() method. Remember that you must make it public and, inside the method, your first action must be super.clone(). Classes that want to allow cloning must implement the marker interface Cloneable. Since the default implementation of Object.clone only performs a shallow copy, classes must also override clone to provide a custom implementation when a deep copy is desired. Basically, if you want to make objects of your class publicly cloneable, you need code like this:


class Test implements Cloneable{
    ...
    public Object clone(){
        try{
            return super.clone();
        }catch ( CloneNotSupportedException e ){
            return null;
        }
    }
...
}

If you are happy with a protected clone, which just blindly copied the raw bits of the object, you don’t need to redefine your own version. However, you will usually want a public one. (Note: You can’t create a private or default scope clone; you can only increase the visibility when you override.)

Possible problems and a solution

Since the clone() method is protected, subclasses have to explicitly agree to be cloneable by overriding this protected method with a public method. All of the Collections classes do this. The subclass also has to implement Cloneable for the default cloning mechanism in Object.clone() to work.

If you have an object that you know has a public clone() method, but you don’t know the type of the object at compile time, you have problems. For instance, say x is declared as an Object. You can’t just call x.clone() because Object.clone() is protected. If Cloneable defined a public clone() method, you could use ((Cloneable) x).clone(), but it doesn’t. You either have to enumerate all the classes that you think x could be, or you have to resort to reflection.

Another problem arises when you try deep copying of a complex object. You’re assuming that the clone() method of all member object variables also does deep copy; this is too risky of an assumption. You must control the code in all classes, or you must know that all classes involved in deep copy operation do such a copy in the right way.

One solution to these problems is to clone using serialization. Serialization is usually used to send objects off somewhere (such as into a file or over the network) so that somebody else can reconstruct them later. You can abuse serialization to immediately reconstruct the object yourself. If the object is serializable at all, the reconstruction should be a faithful copy. In normal uses of serialization, the original object is nowhere near a faithful copy; it could be on the other side of the world at the far end of a network connection. You can be sure that changing the copy will have no effect on the original.

Standard
downloads

Windows Live Photo Gallery

You’ll have to search for it, but this updated version of the Windows Photo Gallery that debuted in Vista is worth the hunt. If you’ve chosen to steer clear of Vista, no worries: It works in XP too.

banner_live.jpg

Blame it on fallout from the U.S. government’s successful antitrust prosecution and the subsequent consent decree, which severely limits what Microsoft can legally bundle with Windows. Ship a bare-bones utility in the OS and no one will complain. Deliver a decent upgrade and you’re on shaky ground. Provide at least three degrees of separation from that OS and you’re okay again.

So you have to work to find this download. But it’s worth the search. It resolves the biggest complaint about the original Photo Gallery—its oversimplified import path. The revised import wizard groups photos by date and time and lets you pick and choose which ones to import. It also adds a whizzy bit of technology that lets you stitch photos together into widescreen panoramas. Its tagging and basic photo editing features are mostly unchanged, which is just fine. All in all, this free download is one of the best programs Microsoft has developed in ages.
Standard
java

Developing real-time applications with Java RTS 2.0

Developing real-time applications with Java RTS 2.0 by Peter Mikhalenko at TechRepublic .

Java Real-Time System (RTS) 2.0 is Sun’s fully compliant implementation of the industry standard set of extensions for the Java platform. It helps you set process priorities according to importance (this is typically not supported in Java software applications).

If you run a normal Java application under Java RTS 2.0, nothing really changes. You’ll start to notice the differences when you need to develop a real-time application. There are, however, significant improvements in the latest version of Java RTS.

Features and enhancements in Java RTS 2.0

A key feature of Java RTS 2.0 is a very predictable method for recycling memory within Java software programs. Using this method, you can determine how and when functions should be executed — down to a millisecond or less.

The Java RTS 2.0 provides the following enhancements to the previous version:

  • Improved determinism for long-running applications.
  • Application monitoring, management, and troubleshooting functionality.
  • A new DTrace probe provider for Java RTS.
  • New MXBean to toggle between deterministic and debugging modes.
  • Modified acquisition of inherited access control for no-heap real-time threads (NHRTs).
  • Minor bug fixes.

Two enhancements in this new version that I think deserve calling special attention to are: its real-time garbage collector and the ability to create and assign a processor set.

Tune the real-time garbage collector
The main feature of Java RTS 2.0 is its real-time garbage collector (RTGC), which makes it fundamentally easier to approach real-time solutions and to control and tune applications. You can convert your existing Java threads to real-time threads (RTTs) by renaming them and yet still having the same semantics. Now you can start using the RTGC; you can set the priority of the thread even higher than the priority of the garbage collector and have no more suffering from the garbage collector. This used to be a very annoying problem for time-critical applications.

Java RTS 2.0 supports two garbage collectors: the RTGC and the non-real-time serial garbage collector. The RTGC, which is the default, might exhibit lower throughput than non-real-time serial garbage collectors, particularly on uniprocessors. For applications that are more sensitive to the collector’s throughput than to the pause times induced by the collector’s execution, the RTGC can be turned off with the -XX:-UseRTGC option. In this case, the non-real-time serial garbage collector is used, and all threads except NHRTs might suffer from pause times caused by garbage collection.

The RTGC is truly concurrent, thus it can be preempted at any time. There is no need to run the RTGC at the highest priority, and there is no stop-the-world phase, where all the application’s threads are suspended during the garbage collection execution. On a multiprocessor, one CPU can be doing some garbage collection work, while an application thread is making progress on another CPU.

The only time RTGC prevents a thread from running is when it has to look at a particular thread’s Java stack, where the local variables and operands are stored; hence, the main potential source of pause time for a given thread is caused by the scanning of its stack. Since a thread is not impacted by the scanning of the other thread stacks, the pause time for a thread is smaller than with non-concurrent garbage collectors.

For additional information, check out the Garbage Collection Guide for Java RTS 2.0.

Create and assign processor sets
For better temporal behavior on a multiprocessor machine, you can create a processor set devoted to the exclusive use of Java RTS 2.0. You can also dedicate a separate processor set to the exclusive use of the NHRTs and the RTTs of Java RTS 2.0. This partition of the available processors ensures the best temporal behavior for these threads by reducing cache thrashing effects.

To request Java RTS 2.0 to assign the NHRT threads to an existing dedicated processor set, use the -XX:RTSJBindNHRTToProcessorSet=<processor_set_id> option. The processors assigned to this processor set should all be set to no-intr to minimize latency and jitter. If this option is set, calling Runtime.availableProcessors from an NHRT will return the number of processors that are available in the processor set that has been assigned to NHRTs. You can use a similar option, RTSJBindRTTToProcessorSet, to bind RTTs to an existing dedicated processor set.

The Solaris operating system allows a machine’s processors to be partitioned into a number of smaller, nonoverlapping processor sets. Processors assigned to a processor set are reserved for the processes explicitly bound to that set. Processes bound to that processor set cannot use those processors. You can create a new processor set with the following command (run with the superuser privileges):

# /usr/sbin/psrset -c
   created processor set <pset id>

Then, you can assign processors to this new processor set with the following command:

# /usr/sbin/psrset -a <pset id> <cpu id>

where <cpu id> refers to one of the on-line processors displayed by the following command:

# /usr/sbin/psrinfo
 <cpu id>     on-line   since mm/dd/yyyy hh:mm:ss
 <cpu id>     on-line   since mm/dd/yyyy hh:mm:ss
 <cpu id>     on-line   since mm/dd/yyyy hh:mm:ss
 <cpu id>     on-line   since mm/dd/yyyy hh:mm:ss

Now you can assign the Java RTS Virtual Machine to run in the new processor set, as follows:

# /usr/sbin/psrset -e <pset id> <Java RTS command line>

How Java RTS differs from the Java HotSpot VM

Java RTS differs in functionality from Java SE and the Java HotSpot VM in a number of ways; it has clocks, timers, class initialization, memory management, and scheduling. In addition, certain issues are only applicable to Java RTS; this includes programming considerations, limitations, bugs, and workarounds.

There are also general differences in the way that Java RTS behaves in comparison to the Java HotSpot VM, which include the following:

  • The default values for the command-line parameters have been tuned for Java RTS and might differ from the default values in the Java HotSpot VM. For instance, the default values for -Xms and -Xmx have been increased for Java RTS.
  • All the memory that is specified by the -Xms and -Xmx parameters is acquired and locked at initialization of the Java HotSpot VM.
  • Java RTS has limited support for the monitoring, management, and troubleshooting tools.
  • Since NHRTs exist, classes and interned strings are never garbage collected. The Real-Time Specification for Java (RTSJ) also prevents objects allocated in static initializers from being garbage collected. You should be aware that such objects are allocated in immortal memory and survive until the Java HotSpot VM exits.
  • Java RTS only provides is the client compiler. The server compiler depends on nondeterministic optimization; therefore, it has been deactivated.
  • Just-In-Time (JIT) compilation is asynchronous by default in Java RTS.
  • Java RTS provides the implementation of variants of inline caches and virtual method inlining. These variants are especially intended for use with the RTGC.
  • Java RTS only provides the 32-bit “client” version of the Java HotSpot VM; the 64-bit version is not supported and using the -server option has no effect.
  • Java RTS 2.0 is currently supported on an UltraSPARC processor or on a Sun x86/x64 platform running Solaris 10 (update 3 or 4 only); Java RTS 2.1 for Linux is available as early access now (real-time Linux versions only): SUSE Linux Enterprise Real Time 10 and Red Hat Enterprise MRG 1.0.
  • It is highly recommended to have a minimum of two processors.

Additional resources about Java RTS

Blogged with Flock

Standard