Generics and Legacy Code

My previous article “Generics in Java” was a mere introduction to the generics. You can say that it was just the tip of the ice burg. This time we will go a bit inside generics and discuss about the issues in integrating generic and non-generic code..

Imagine we have an ArrayList, of type Integer, and we're passing it into a method from a class whose source code we don't have access to. Will this work?

// a Java 5 class using a generic collection
import Java.util.*;
public class TestLegacy {
public static void main(String[] args) {
List myList = new ArrayList();
// type safe collection
myList.add(4);
myList.add(6);
Adder adder = new Adder();
int total = adder.addAll(myList) ;
// pass it to an un-typed argument
System.out.println(total);
}
}

The older, non-generics class we want to use:

import Java.util.*;
class Adder {
int addAll(List list) {
// method with a non-generic List argument,
// but assumes (with no guarantee) that it will be Integers
Iterator it = list.iterator();
int total = 0;
while (it.hasNext()) {
int i = ((Integer)it.next()).intValue();
total + = i;
}
return total;
}
}
Yes, this works just fine. You can mix correct generic code with older non-generic code, and everyone is happy.

In that example, method wasn't doing anything except getting the Integer (using a cast) from the list and accessing its value. So, there was no risk to the caller's code, but the legacy method might have blown up if the list passed in, contained anything but Integers (which would cause a ClassCastException).

But now imagine that you call a legacy method that doesn't just read a value but adds something to the ArrayList? Will this work?

import java.util.*;
public class TestBadLegacy {
public static void main(String[] args) {
List myList = new ArrayList();
myList.add(4);
myList.add(6);
Inserter in = new Inserter();
in.insert(myList); // pass List to legacy code
}
}
class Inserter {
// method with a non-generic List argument
void insert(List list) {
list.add(new Integer(42)); // adds to the incoming list
}
}

Sure, this code works. It compiles, and it runs. The insert() method puts an Integer into the list that was originally typed as , so no problem.

But…what if we modify the insert() method like this:

void insert(List list) {
list.add(new String("42")); // put a String in the list passed in
}

Will that work? Yes, sadly, it does! It both compiles and runs. No runtime exception.

How can that be?

Remember, in the older legacy code i.e. before java 5, you were allowed to put anything into a collection. So, in order to support your legacy code, Java 5 compiler is forced to let you to compile your new type safe code, even though your new code invokes an old method of some pre-generics class, which was totally unaware of the type safety.

In the above example with the legacy insert() method that adds a String, the compiler generated a warning:

javac TestBadLegacy.java
Note: TestBadLegacy.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Remember that compiler warnings are NOT considered a compiler failure. The compiler generated a perfectly valid class file from the compilation, but it was kind enough to tell you by saying, in so many words, "I seriously hope you know what you are doing because this old code has NO respect (or even knowledge) of your typing, and can do whatever the heck it wants to your precious ArrayList<>."

The reason the compiler produces a warning is because the method is ADDING something to the collection! In other words, the compiler knows there's a chance the method might add the wrong thing to a collection the caller thinks is type safe.

There's one Big Truth you need to know to understand why it runs without problems—the JVM has no idea that your ArrayList was supposed to hold only Integers. The typing information does not exist at runtime! All your generic code is strictly for the compiler. Through a process called "type erasure," the compiler does all of its verifications on your generic code and then strips the type information out of the class bytecode. At runtime, ALL collection code—both legacy and new Java 5 code you write using generics—looks exactly like the pre-generic version of collections. None of your typing information exists at runtime. In other words, even though you WROTE

List myList = new ArrayList();

By the time the compiler is done with it, the JVM sees what it always saw before Java 5 and generics:

List myList = new ArrayList();

The compiler even inserts the casts for you—the casts you had to do to get things out of a pre-Java 5 collection.

Always keep in mind, even though you are using generics, no type information is available at runtime. The fact is, you don't NEED runtime protection…until you start mixing up generic and non-generic code.

The only advice we have is to pay very close attention to those compiler warnings:


javac TestBadLegacy.java

Note: TestBadLegacy.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

This compiler warning isn't very descriptive, but the second note suggests that you recompile with -xlint:unchecked. If you do, you'll get something like this:


javac -Xlint:unchecked TestBadLegacy.java

TestBadLegacy.java:17: warning: [unchecked] unchecked call to
add(E) as a member of the raw type java.util.List
list.add(new String("42"));
^
1 warning

When you compile with the -Xlint:unchecked flag, the compiler shows you exactly which method(s) might be doing something dangerous. In this example, since the list argument was not declared with a type, the compiler treats it as legacy code and assumes no risk for what the method puts into the "raw" list.


Just remember that the moment you turn that type safe collection over to older, non-type safe code, your protection vanishes. Again, pay very close attention to compiler warnings, and be prepared to see issues like we just discussed….

References:

• Sun Certified Programmer for Java 5 Study Guide by Kathy Sierra and Bert Bates.

Video Conferencing

This article is authored by one of our readers Ms. Soniya Kelly, London. She has done all the research and gathered the content to make this article more informative and interesting..

Video conferencing is getting popular with each passing day. It is seen as the most convenient way of communication for business in all the sectors and the industries. Unlike the voice conferences, this telecommunication method uses interactive telecommunication technology and audio and visual aids for communication. The individuals thus communicating by this process can have more personal interaction than in voice communication.



What is video conference??

A videoconference (also known as a videoteleconference) is a set of interactive telecommunication technology which allows two or more locations to interact via two-way video and audio transmissions simultaneously. It has also been called visual collaboration and is a type of groupware. It differs from videophone in that it is designed to serve a conference rather than individuals.



How video conferencing system works??

Video conferencing systems vary from entry-level systems using a desktop PC through to advanced 'installed' systems in boardrooms and meeting rooms.

* Desktop video conferencing - This system usually uses a small camera located on top of the PC or workstation monitor. The actual video is usually displayed in a small window, and shared applications, such as a shared whiteboard are often used.

* Studio-based systems - This system uses a studio (though usually a normal meeting room with portable equipment set up when required) specially equipped for video conferencing. This will normally include one or more cameras, microphones, one or more monitors and possibly other equipment such as an overhead camera for document viewing.

Whatever system is used a broadband connection is crucial, as higher speeds mean higher quality conferences. A connection of 384Kbps is the standard speed for most conferences.



Why should we welcome this technology??

In today’s challenging economy, businesses are looking for ways to cut travel costs, without losing the personal element of face-to-face meetings. According to a new survey, financial pressures and other widespread business trends from globalization to going green are increasing the adoption of videoconferencing in offices nationwide.

According to one research study reports that 23% of respondents have deployed or are planning to implement telepresence solutions within a year – a figure that may climb as businesses look for ways to maximize their bottom line. To support high-quality conferencing solutions, the study indicates that 76% of video calls now run on IP networks – an increase of 9% from a year ago. Furthermore, increasingly popular broadband-enabled video services mean users only need an inexpensive Webcam to connect visually.

In addition to the financial savings videoconferencing brings, there are promising green benefits. The American Consumer Institute report on the economic and environmental benefits of broadband indicates that greenhouse gas emissions could be reduced by 200 million tons if 10% of airline travel is replaced by teleconferencing over the next ten years. Videoconferencing also holds tremendous potential for e-learning. For example, 30% of Alaska’s school districts now offer classes via videoconferencing, which allows students in remote villages to access diverse courses.

Save time and travel costs - Video conferencing allows you to increase flexibility within your organisation. Staff can work in remote locations saving on the stress and costs of commuting. Client meetings can also occur more often and on an ad hoc basis making meeting attendance more convenient. It can also make meetings more likely to happen.
Help the environment - Reducing the need to travel also benefits the environment. BT director Adrian Hosford says the UK has the worst traffic congestion in Europe and that "increasing the use of teleworking is essential to reducing the amount of personal and business travel".
Present your case - With most systems you can display papers using electronic document camera or show information direct from your personal computer. You can also play a pre-recorded video, or even tape your own presentation - all from the comfort of your own office. This content could consist of educational resources, presentation materials, or technical drawings to mention but a few.
Collaborate - Video conferencing can also benefit team working and allow colleagues to discuss and debate issues much more comprehensively than can be achieved by phone alone.


Problems with video conferencing..

Some observers argue that two outstanding issues are preventing videoconferencing from becoming a standard form of communication, despite the ubiquity of videoconferencing-capable systems. These issues are:

1. Eye Contact: It is known that eye contact plays a large role in conversational turn-taking, perceived attention and intent, and other aspects of group communication. While traditional telephone conversations give no eye contact cues, videoconferencing systems are arguably worse in that they provide an incorrect impression that the remote interlocutor is avoiding eye contact. Telepresence systems have cameras located in the screens that reduce the amount of parallax observed by the users. This issue is also being addressed through research that generates a synthetic image with eye contact using stereo reconstruction.

2. Appearance Consciousness: A second problem with videoconferencing is that one is on camera, with the video stream possibly even being recorded. The burden of presenting an acceptable on-screen appearance is not present in audio-only communication. Early studies by Alphonse Chapanis found that the addition of video actually impaired communication, possibly because of the consciousness of being on camera.

The issue of eye-contact may be solved with advancing technology, and presumably the issue of appearance consciousness will fade as people become accustomed to videoconferencing.

Every coin have two sides...Like that ‘Video conferencing’ also have advantages and drawbacks but with the flexibility and versatility it offers to the different business, it surely offers the business enterprises a solution for connectivity which can earn profits for the enterprise which counts a lot for enterprises...