320 replies
by narendrn
When I was first introduced to delegates, I found it quite confusing compared to the Java Listener concept. As we know, Java Listeneres use the classic Command design pattern to implement call-backs (implement a standard interface and the method e.g. OnMouseClick())
But after understanding delegates, I have realised that delegates are a bit more flexible than Java Listeners. By using a delegate, U are free to use any method of any object- just the signature of the method should match.
They allow easy binding of event handlers and other callback mechanisms, without the use of a separate class implementing a specific listener interface (which is the Java approach for callbacks).
Basically, instead passing a callback function via an object of known interface that both communicating parties agree on, delegates only need the two parties to use the same function signature
An interesting article regarding this can be found at:
http://blog.monstuff.com/archives/000037.html#more
by narendrn
A variable passed as an out argument need not be initialized. However, the out parameter must be assigned a value before the method returns.
An argument passed to a ref parameter must first be initialized. Compare this to an 'out ' parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.
Now the big question is why did Microsoft go thru the pain of having both 'ref' and 'out' ?
The answer is in the snippet below:
The two parameter passing modes addressed by out and ref are subtly different, however they are both very common. The subtle difference between these modes leads to some very common programming errors.
These include:
not assigning a value to an out parameter in all control flow paths
not assigning a value to variable which is used as a ref parameter
Because the C# language assigns different definite assignment rules to these different parameter passing modes, these common coding errors are caught by the compiler as being incorrect C# code.
The crux of the decision to include both ref and out parameter passing modes was that allowing the compiler to detect these common coding errors was worth the additional complexity of having both ref and out parameter passing modes in the language.
by narendrn
The .NET API makes asynchronous programming a breeze....
U can make a async call to any method and what amazed me was the simplicity !!!
We just have to make use of the magic of delegates...
Define a delegate with the same signature as the method you want to call; the common language runtime automatically defines BeginInvoke and EndInvoke methods for this delegate, with the appropriate signatures.
The BeginInvoke method is used to initiate the asynchronous call. It has the same parameters as the method you want to execute asynchronously, plus two additional parameters that will be described later. BeginInvoke returns immediately and does not wait for the asynchronous call to complete. BeginInvoke returns an IasyncResult, which can be used to monitor the progress of the call.
The EndInvoke method is used to retrieve the results of the asynchronous call. It can be called any time after BeginInvoke; if the asynchronous call has not completed, EndInvoke will block until it completes. The parameters of EndInvoke include the out and ref parameters ( ByRef and ByRef in Visual Basic) of the method you want to execute asynchronously, plus the IAsyncResult returned by BeginInvoke.
So after making a Async call, we have the following options:
- Do something and then block till the call completes.
- Poll continously to see it call is complete
- Assign a call-back delegate (AsyncCallBack)
I found this feature of .NET really really cool...especially in my threading applications.
by narendrn
A race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled. Race conditions can lead to unpredictable results and subtle program bugs
In Java, the Object class provides a collection of methods ? wait, notify, and notifyAll ? to help threads wait for a condition and notify other threads when that condition changes.
by narendrn
While working on XML-driven applications I often used to dislike writing DTD or Schema files..The syntax was cryptic and difficult to remember.
In the .NET SDK, there is a cool tool called XSD.exe that can take a sample XML file and automatically generate a schema-definition file for it.
The following command generates an XML schema from myFile.xml and saves it to the specified
directory.
xsd myFile.xml /outputdir:myOutputDir
by narendrn
I always wondered why does the Java language mandate that wait() should be kept inside a synchronized block. (Especially bcoz wait() releases the lock of the object immediately)
This is required by the language, and ensures that wait and notify are properly serialized. In practical terms, this eliminates race conditions that could cause the "suspended" thread to miss a notify and remain suspended indefinitely.
by narendrn
We often require a main thread of a application to keep waiting (and not end).
For Console applications, we can just block with a Console.Read() method.
For other applications, we tend to write a infinite loop like -- while(true){}
But the above statement keeps on wasting a lot of computational cycles.
A much cleaner and cool approach would be :--
java.lang.Object sync = new java.lang.Object();
synchronized (sync) { sync.wait(); }
by narendrn
Here are a couple of sites which have the best "audio-visual" tutorials (I have seen) on TCP/IP networking concepts. A must see..
by narendrn
I often was confused as to why a MAC address is required for a network node when we have a IP address. The MAC address is actually a hardware address that is assigned by the manufacturer and is gauranteed to be unique.
Basically the MAC address is used in the Data-link layer and the IP address is used in the Network layer. For e.g. Ethernet uses MAC address to find other hosts.
The ARP protocol does the mapping btw the MAC address and the IP address.
by narendrn
In addition to the pluggable look and feel UI Managers that Swing provides, each PLAF can also have various themes associated with it. These themes allow U to change some common properties such as 'font size', 'background color of a component' etc.
The abstract javax.swing.plaf.metal.MetalTheme class offers about fifty settings that let you customize the fonts and colors of the Swing components. By creating different subclasses, you can swap many of the properties at once when you change the look and feel.
MetalTheme theme = new MyCustomTheme();
MetalLookAndFeel.setCurrentTheme(theme);
UIManager.setLookAndFeel(new MetalLookAndFeel());
For an example of theme usage, try out the Metalworks demonstration that comes with the Java 2 SDK distribution. Simply change the current directory to the demo/jfc/Metalworks directory, and run the demonstration with the following command:
java -jar Metalworks.jar
by narendrn
Prior to JDK 1.4, it was not easy to share a file between multiple processes (Java or non Java). IT involved the use of native code. But in JDK 1.4 NIO (non blocking IO) was introduced with the concept of channels and file-locks.
The FileLock class, which is part of the java.nio.channels package, represents a file lock. You can use a file lock to restrict access to a file from multiple processes. In addition, you have the option of restricting access to an entire file or just a small region of it. A file lock is either shared or exclusive. A shared lock supports read access from multiple processes, while an exclusive lock is typically used for writing. Because a lock is at the file level, you should not use it to restrict access to a file from multiple threads in a single process. If you use a file lock in multiple threads, none of the threads would be restricted from accessing the file. Only external processes are restricted.
by narendrn
In one of my .NET projects, we landed up in a situation where there was a circular compilation dependency between 2 projects. It would tough to compile both the projects...so we resorted to first commenting out some code in the second project and then compiling and getting a "dummy" dll which we can use furthur for compilation.
But VS.NET can automatically take care of such circular dependencies...The trick is very simple. Just add both the projects to a common solution. And in the 'Add Reference' option, do not add the DLL directly, but add the 'Project' as a reference. (3rd Tab in Add Reference window)
The VS.NET environment automatically takes care of circular dependencies.
Similarly in Java, the javacc compiler automatically takes care of circular dependencies. :)
by narendrn
A terminal is just a window that people type commands in. A console can be used as aterminal also, but is connected to the system console which is where the kernel andsyslog will output information to.
by narendrn
Just type 'drivers' on a command prompt or in the 'Run' option. :)
I found this damn handy bcoz I often used to forget the full path where I can put DNS entries.
by narendrn
In one of my projects, I often had to log on (telnet) to a server and execute a number of steps..
I desparately wanted some tool which would automate this for me...i.e. pass commands to the server thru telnet, wait for output etc.
"Tera Term" is a cool utility that allows U to write scripts using a simple language..(It took me just 5 mins to get the basic commands) The scripts have a *.ttl extension.
Cool handy tool...A must have :)
by narendrn
Windows comes with a cool utility known as 'netstat' that can be used to find out all the current TCP or UDP connections on Ur PC.
Also U can find out the port used on Ur PC for a service.
e.g. if U telnet to some machine U know that U are using port '23' on that machine, but what is the port on Ur machine?
Just type 'netstat -n' on the command prompt.
by narendrn
I used to maintain my technical blog at http://naren.tblog.com
But I found the "Blogger" site by google so user-friendly and cool that I am transferring my technical blogs to here.
by narendrn
In ASP.NET, web.config contains a tag.
<globalization culture="en-GB" requestencoding="utf-8" responseencoding="utf-8">
When the culture is "en-US" and we print a DateTime object, we get it in the format "mm/dd/yyyy" whereas if U change the culture to "en-GB" then the date.toString() would return a string in the format "dd/mm/yyyy".So our code cannot assume the date, month to be in a specific format for parsing. Very very imp tip for localisation !!!!
by narendrn
In java, when you try to print a null reference, what do U get?
For e.g. Object obj = null;System.out.println(obj);
What gets printed is "null".
So basically a null reference when converted to a string results in "null".
But in Csharp, the same code will print a empty string
Object obj = null;
Console.WriteLine(obj);
Very imp difference for java developers learning C#
Another important difference is while Type-Casting or Boxing/UnBoxing as it is known in C#.Java does not allow us to cast a reference type to a primitive type.So the following code in Java would throw an compilation error:
boolean b = (boolean)getSomeObject();
Assume getSomeObject() method has the signature:
public object getSomeObject()
But in C#, it is possible to type-cast an reference type to an primitive. So the following code would not give a compilation error.
bool b = (bool)getSomeObject();
But at runtime, if getSomeObject() returns a 'null' , then we would get a 'NullReferenceException'
A 'null' can be type-casted to any object reference type, but not to a primitive type So in C#, we need to be very careful about this fact
by narendrn
How can we write a customCollection object which behaves the same way as a ASP.NET session object or Application object, i.e. retrieve the values using indexes.
For e.g. we can retrieve a object from Session as :
object obj = Session["key"]; //to retrieve
Session["key"] = obj; //add or set a value in Session.
Writing our own Collection object which behaves in a similar manner is very simple, using Indexes in C #See code below:
class MyCollection
{
private Hashtable hashTable = new Hashtable();
public object this [object index]
{
get{return hashTable[index];} set{hashTable[index] = value;}
}
}
Now we can use MyCollection object as shown below:
MyCollection myCollection = new MyCollection();
myCollection["Naren"] = "Swetha";
Console.WriteLine("value >> " + myCollection["Naren"]);
That's it....
by narendrn
The below code is in .NET C#
public ArrayList GetAllFiles(string directory)
{
ArrayList totalFilesList = new ArrayList(10);
string[] files = Directory.GetFiles(directory);//add all files in that current folder.totalFilesList.AddRange(files);//Check if the current directory has sub-directories
string[] subDirs = Directory.GetDirectories(directory);//if yes, then call recursive functions..
if(subDirs.Length > 0)
{//now look for all files in current folder's sub-dir's.
foreach(string subDir in subDirs)
{
ArrayList tempArrayList = GetAllFiles(subDir);
totalFilesList.AddRange(tempArrayList);
}
}
return totalFilesList;
}
by narendrn
Suppose I have a table as below:
Table Project
{
ProjectID int
Manager int (secondary key)
Architect int (secondary key)
Client int (secondary key)
}
Table Contact
{
ContactID int (primary key)
Name string
}
Now I want to show the Project table with names of Manager and Architect and the client.
A "join" or a "union" will not work...The solution is very simple:
select Project.ProjectID, a.FirstName as Manager, b.firstname as Architect, c.FirstName as Client from Project,
Contact a,
Contact b,
Contact c
where a.contact_id = project.manager and
b.contact_id = project.architect and
c.contact_id = project.client
by narendrn
Visual Studio .NET has a very stupid problem...If Ur dotnet assembly size is above 64kb then Intellisense locks the dll and so the build fails.
Solutions for the problem are given at:
http://support.microsoft.com/kb/313512/EN-US/
by narendrn
AWT: The idea was to wrap the native GUI widgets of the various operating systems with a platform-independent Java API called Abstract Window Toolkit (AWT). Only common widgets such as text field, text area, check box, radio button, list, and push button were supported by AWT. The graphics and imaging features were also very limited. That was, at best, enough for building simple applets.
SWING: is one of the most complex GUI frameworks ever developed. It has a complete set of GUI components ranging from buttons and text fields to tables, trees, and styled text editors. These components do not rely on the native widgets of the operating system; instead, Swing components are painted using graphic primitives such as lines, rectangles, and text. The painting is delegated to a look and feel (L&F) plug-in that can imitate the native L&F. Swing also has a platform-independent L&F called "Metal." JBuilder, uses Swing, and its speed is quite good.
Standard Widget Toolkit (SWT) is the GUI toolkit developed by IBM for its Eclipse IDE. SWT can be used outside of the Eclipse environment and offers direct access to the native GUI features of the operating system. Therefore, SWT-based Java applications have native GUIs and can be integrated with other native applications and components. SWT delegates to native widgets for common components (such as labels, lists, tables, and so on) as AWT does, while emulating in Java more sophisticated components (for example, toolbars are emulated when running on Motif) similarly to Swing's strategy.SWT has been designed to be as inexpensive as possible. This means (among the other things) that it is native-oriented. Anyway, it differs from AWT in a number of details. SWT provides different Java implementations for each platform, and each of these implementations calls natively (through the Java Native Interface, JNI) the underlying native implementation. The old AWT is different in that all platform-dependent details are hidden in C (native) code and the Java implementation is the same for all the platforms.
by narendrn
With JDK 1.2, Sun introducted the Java Collection Framework, a cool API for data-structures in Java. At the base of the heirarchy were collection interfaces like:
List: A collection that is ordered and whose members can be accessed by index. A list can also contain duplicates and null values.
Set: A collection that is not ordered and hence there are no methods that allow to access members thru a index. Also a Set does not allow duplicates and atmost one null value.
Though I personally feel that the JDK Collection framework is quite comprehensive and should suffice most development needs, it is good to know about some other alternatives:
1) Jakarta Commons Collections - An open source initiative that contains some extra cool collections like MultiMap etc.
2) JGL (Java Generic Library) - A port of the C++ STL (Standard tag library) to the Java language. Thought I was first impressed by this package, I think this API would appleal more to those from the C++ background. Also the latest version is no longer free, I believe.
by narendrn
Since college days, we have been seeing the words 'foo' and 'bar' in a hell lot of programs...So what do these variable names mean ?...
The following links provide some really amusing information:
http://www.catb.org/~esr/jargon/html/F/foo.html
http://kb.indiana.edu/data/aetq.html?cust=379462.50587.30
by narendrn
Recently a few guys in my team were using a tool known as VMWare for simulating different operating systems on a single machine. Here's some info on how this is done:
VMWare hosts each guest operating system in a separate, secure virtual machine. Each virtual machine (VM) has its own virtual CPU, memory, disk, etc. and all of the virtual hardware is mapped to your computer's real hardware. Each virtual machine also comes complete with its own BIOS that can be edited the same way you'd edit the real BIOS on the computer that VMWare is running on. This lets you customize your virtual machines and control all of the usual stuff that you can control via your PC's actual BIOS.
by narendrn
I should have not been totally suprised by this news, as it is natural for a company to have some "competitive systems" where they can benchmark their products with the other products.
But it looks like MS is trying to play a different ball game. It "says" (believe it or not) that it wants to bridge the gap between the opensource community and MS. It's hard to say what MS strategy really is, but the truth is, today open-source software has become a force to reckon with !!!
http://www.microsoft-watch.com/article2/0,1995,1813672,00.asp
by narendrn
The following links have some good Java questions that one can expect in interviews:
http://java.sys-con.com/read/48839_2.htm
http://java.sys-con.com/read/46228.htm
Also interesting is some points given in the second link regarding the trouble is finding good Java developers today.
by narendrn
This eternal debate keeps coming up from time to time.
This time the debate was sparked by a article in Javaworld at http://www.javaworld.com/javaworld/jw-05-2005/jw-0509-architect.html
All the comments that were posted in response were very very interesting:
http://www.theserverside.com/news/thread.tss?thread_id=33809&News05_10_05-click
http://indicthreads.com/blogs/209/java_architect_developer.html
Also I was amused to hear what Martin Fowler of "ThoughtWorks" had to say about this topic.
http://www.martinfowler.com/ieeeSoftware/whoNeedsArchitect.pdf
In Agile methodologies, there is more focus on keeping components flexible and ready for change, hence the role of a architect also changes...Interesting read :)
Some really amusing comments are listed below : (who says developers do not have a good sense of humor)
- Of course there are organization where you have PowerPoint-architects who hide their ignorance and lack of actual knowledge behind stack loads of nice-looking high-level block-diagrams that do absolutely nothing and will never be looked upon a second time after they have been presented to the project board or whoever.
- Any of the following is much better definition of a (Java) architect :1. One who does not know how to start a java JVM. 2. One talks about UML all the times and present you a class diagram by copying from Gang of Four pattern book as his design.3. One who has never managed to write more than 100 lines of codes successfully.4. One who is the buddy of the VP of Engineering or CTO.
by narendrn
While Microsoft Visual Studio .NET is the standard-bearer for .NET development, its hefty price tag and overwhelming features can often push developers away from it. Thankfully, a variety of alternative IDEs (Integrated Development Environment) are available. Here's a high-level view of these alternatives.
ASP.NET Web Matrix
Microsoft provides the freely available ASP.NET Web Matrix tool for developing ASP.NET-based applications. Microsoft describes it as a community-supported, easy-to-use WYSIWYG application development tool for ASP.NET. It includes database connectivity, Web services, mobile platform support, and support for multiple languages. It is supported on Windows 2000 and XP and Internet Explorer 5.5 or greater with the .NET Framework installed. Finally, it includes a development Web server so IIS is not required.
SharpDevelop
SharpDevelop is a freely available open source IDE built with the C# language. It provides a great example of what you can achieve with the .NET platform, but it doesn't restrict you to C#. It is similar to Visual Studio .NET in both appearance and features. It allows you to develop all types of applications including ASP.NET, Windows Forms, and console. At this time, it is only supported on the Windows platform.
PrimalCode
PrimalCode is a commercially available .NET IDE available from Sapien. The company describes it as an innovative .NET development environment, incorporating complete scripting and .NET development capability in a compact size that works with your existing hardware. PrimalCode includes two other Sapien tools: PrimalScript and PrimalDiff. In addition to .NET support, PrimalCode supports more than 30 languages including Perl, classic ASP, PHP, ColdFusion, VBScript, JSP, and WMI. Also, it includes a source code control system. It is available for the Windows platform with a trial download available. The download version is available for $249 USD.
Antechinus C# Editor
Antechinus C# Editor allows you to develop C# code including both Windows Forms and ASP.NET applications. It resembles Microsoft FrontPage, allowing you to publish an application to the appropriate Web location. It is integrated with the various tools installed with the .NET Framework, and it includes many features to make your life easier like bookmarking, documentation, color-coding, templates, and so forth. It is available for $49.95 USD for the Windows platform.
Eclipse
Eclipse is an open, extensible IDE framework developed by IBM. It was originally developed for the Java language. It is built on a mechanism for discovering, integrating, and running modules called plug-ins. That is, a tool provider writes a tool as a separate plug-in that operates on files in the workspace and surfaces its tool-specific user interface in the IDE. One such plug-in is the C# Plugin from Improve Technologies. It allows you to work with C# code, but the creation of C# projects or integrated development of ASP.NET or Windows Forms' applications is not supported. Both Eclipse and the Improve C# Plugin are freely available for Windows and Linux.
MonoDevelop
MonoDevelop is a freely available IDE for the Linux platform. It is connected with the Mono project. It is a simple IDE allowing development of C# code. It includes various Visual Studio .NET features like code completion, extensive help, class management, and an integrated debugger. It is still in the early stages of development so it will continue to add features, including support for building GUI interfaces. You should monitor its site to keep up with associated developments.
CodeWright
Borland has been an active member of the development tool community for many years, and they are an active participant in the continuing evolution of Eclipse as well. Its CodeWright tool is a powerful file editing system. It includes peer-to-peer connectivity for remote communication and file editing. Basically, I think of it as a text editor on steroids. It is available as a standalone tool as well as an add-in for Visual Studio .NET. The downside is that the CodeWright product is being discontinued so future support is still to be determined.
by narendrn
A type must implement Finalize() when it uses unmanaged resources such as file handles or database connections that must be released when the managed object that uses them is reclaimed.
But executing Finalize() has its performance bottlenecks. Read the below articles for more info.
http://msdn.microsoft.com/msdnmag/
issues/1100/GCI/default.aspx
http://msdn.microsoft.com/msdnmag/
issues/1200/GCI2/default.aspx
Hence it is better if a Dispose() method is implemented and developers are encouraged to call Dispose() or Close(). We can always have Finalize() as a back-up in case the developer forgets to call Dispose(). For this we need to use the SuppressFinalize() method to prevent double execution of clean-up code.
GC class has a SuppressFinalize() method that can be called from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.
by narendrn
Two excellent articles on how Garbage Collection works in .NET.
A "MUST READ" for all .NET developers..
http://msdn.microsoft.com/msdnmag/
issues/1100/GCI/default.aspx
http://msdn.microsoft.com/msdnmag/
issues/1200/GCI2/default.aspx
Excerpt from the article:
How does the garbage collector know if the application is using an object or not?
As you might imagine, this isn't a simple question to answer.Every application has a set of roots. Roots identify storage locations, which refer to objects on the managed heap or to objects that are set to null. For example, all the global and static object pointers in an application are considered part of the application's roots. In addition, any local variable/parameter object pointers on a thread's stack are considered part of the application's roots. Finally, any CPU registers containing pointers to objects in the managed heap are also considered part of the application's roots. The list of active roots is maintained by the just-in-time (JIT) compiler and common language runtime, and is made accessible to the garbage collector's algorithm.
Now, the garbage collector starts walking the roots and building a graph of all objects reachable from the roots. For example, the garbage collector may locate a global variable that points to an object in the heap.
Once this part of the graph is complete, the garbage collector checks the next root and walks the objects again. As the garbage collector walks from object to object, if it attempts to add an object to the graph that it previously added, then the garbage collector can stop walking down that path. This serves two purposes. First, it helps performance significantly since it doesn't walk through a set of objects more than once. Second, it prevents infinite loops should you have any circular linked lists of objects.Once all the roots have been checked, the garbage collector's graph contains the set of all objects that are somehow reachable from the application's roots; any objects that are not in the graph are not accessible by the application, and are therefore considered garbage. The garbage collector now walks through the heap linearly, looking for contiguous blocks of garbage objects (now considered free space). The garbage collector then shifts the non-garbage objects down in memory (using the standard memcpy function that you've known for years), removing all of the gaps in the heap. Of course, moving the objects in memory invalidates all pointers to the objects. So the garbage collector must modify the application's roots so that the pointers point to the objects' new locations. In addition, if any object contains a pointer to another object, the garbage collector is responsible for correcting these pointers as well.
by narendrn
Weak references reduce the memory pressure placed on the managed heap by large objects.
When a root points to an object, the object cannot be collected because the application's code can reach the object. When a root points to an object, it's called a strong reference to the object. However, the garbage collector also supports weak references. Weak references allow the garbage collector to collect the object, but they also allow the application to access the object.
------------------------------------------------------
Void Method() {
Object o = new Object(); // Creates a strong reference to the
// object.
// Create a strong reference to a short WeakReference object.
// The WeakReference object tracks the Object.
WeakReference wr = new WeakReference(o);
o = null; // Remove the strong reference to the object
o = wr.Target;
if (o == null) {
// A GC occurred and Object was reclaimed.
} else {
// a GC did not occur and we can successfully access the Object
// using o
}
}
---------------------------------------------
Once you've created a weak reference to an object, you usually set the strong reference to the object to null. If any strong reference remains, the garbage collector will be unable to collect the object.
To use the object again, you must turn the weak reference into a strong reference. You accomplish this simply by calling the WeakReference object's Target property and assigning the result to one of your application's roots. If the Target property returns null, then the object was collected. If the property does not return null, then the root is a strong reference to the object and the code may manipulate the object. As long as the strong reference exists, the object cannot be collected.
Note: It seems that "weak" references in .NET are equivalent to "soft" references in Java.
by narendrn
The GC mechanisms in Java and .NET are the same with some minor differences. Read the following articles for more details:
http://www.javaworld.com/javaworld/jw-12-2001/jw-1207-java101.html
http://www.javaworld.com/javaworld/jw-01-2002/jw-0104-java101.html
http://www.javaworld.com/javaworld/jw-01-2002/jw-0104-java101guide.html
by narendrn
The Reference API in Java can leave any sane person fully confused !!!..I tried to make sense of what the different types of references are and what purpose do they solve.
I am still not crystal clear about the usability of all these references, but I hope I will understand someday.
Referent
An object that is softly, weakly, or phantomly referenced from inside a SoftReference, WeakReference, or PhantomReference object, respectively.
Soft references:
The garbage collector might or might not reclaim a softly reachable object depending on how recently the object was created or accessed, but is required to clear all soft references before throwing an OutOfMemoryError.
Weakly reachable objects are finalized some time after their weak references have been cleared. The only real difference between a soft reference and a weak reference is that the garbage collector uses algorithms to decide whether or not to reclaim a softly reachable object, but always reclaims a weakly reachable object.
Phantomly reachable objects are objects that have been finalized, but not reclaimed.
The garbage collector will never clear a phantom reference. All phantom references must be explicitly cleared by the program.
An excellent article explaining GC in Java is given at
http://www.artima.com/insidejvm/ed2/gc17.html
Excerpts from the article:
--------------------------
Note that whereas the garbage collector enqueues soft and weak reference objects when their referents are leaving the relevant reachability state, it enqueues phantom references when the referents are entering the relevant state. You can also see this difference in that the garbage collector clears soft and weak reference objects before enqueueing them, but not phantom reference objects. Thus, the garbage collector enqueues soft reference objects to indicate their referents have just left the softly reachable state. Likewise, the garbage collector enqueues weak reference objects to indicate their referents have just left the weakly reachable state. But the garbage collector enqueues phantom reference objects to indicate their referents have entered the phantom reachable state. Phantom reachable objects will remain phantom reachable until their reference objects are explicitly cleared by the program.
The garbage collector treats soft, weak, and phantom objects differently because each is intended to provide a different kind of service to the program. Soft references enable you to create in-memory caches that are sensitive to the overall memory needs of the program. Weak references enable you to create canonicalizing mappings, such as a hash table whose keys and values will be removed from the map if they become otherwise unreferenced by the program. Phantom references enable you to establish more flexible pre-mortem cleanup policies than are possible with finalizers
To use the referent of a soft or weak reference, you invoke get() on the reference object. If the reference hasn't been cleared, you'll get a strong reference to the referent, which you can then use in the usual way. If the reference has been cleared, you'll get null back. If you invoke get() on a phantom reference object, however, you'll always get null back, even if the reference object hasn't yet been cleared. Because the phantom reachable state is only attained after an object passes through the resurrectable state, a phantom reference object provides no way to access to its referent. Invoking get() on a phantom reference object always returns null, even if the phantom reference hasn't yet been cleared, because if it returned a strong reference to the phantom reachable object, it would in effect resurrect the object. Thus, once an object reaches phantom reachability, it cannot be resurrected.
Virtual machine implementations are required to clear soft references before throwing OutOfMemoryError, but are otherwise free to decide when or whether to clear them. Implementations are encouraged, however, to clear soft references only when the programs demand for memory exceeds the supply, to clear older soft references before newer ones, and to clear soft references that haven't been used recently before soft references that have been used recently.
Soft references enable you to cache in memory data that you can more slowly retrieve from an external source, such as a file, database, or network. So long as the virtual machine has enough memory to fit the softly referenced data on the heap together with all the strongly referenced data, the soft reference will in general be strong enough to keep the softly referenced data on the heap. If memory becomes scarce, however, the garbage collector may decide to clear the soft references and reclaim the space occupied by the softly referenced data. The next time the program needs to use that data, it will have to be reloaded from the external source. In the mean time, the virtual machine has more room to accommodate the strongly (and other softly) referenced memory needs of the program.
Weak references are similar to soft references, except that whereas the garbage collector is free to decide whether or not to clear soft references to softly reachable objects, it must clear weak references to weakly reachable objects as soon as it determines the objects are weakly reachable. Weak references enable you to create canonicalizing mappings from keys to values. The java.util.WeakHashMap class uses weak references to provide just such a canonicalizing mapping. You can add key-value pairs to a WeakHashMap instance via the put() method, just like you can to an instance of any class that implements java.util.Map. But inside the WeakHashMap, the key objects are held via weak reference objects that are associated with a reference queue. If the garbage collector determines that a key object is weakly reachable, it will clear and enqueue any weak reference objects that refer to the key object. The next time the WeakHashMap is accessed, it will poll the reference queue and extract all weak reference objects that the garbage collector put there. The WeakHashMap will then remove from its mapping any key-value pairs for keys whose weak reference object showed up in the queue. Thus, if you add a key-value pair to a WeakHashMap, it will remain there so long as the program doesn't explicitly remove it with the remove() method and the garbage collector doesn't determine that the key object is weakly reachable.
Phantom reachability indicates that an object is ready for reclamation. When the garbage collector determines that the referent of a phantom reference object is phantom reachable, it appends the phantom reference object to its associated reference queue. (Unlike soft and weak reference objects, which can optionally be created without associating them with a reference queue, phantom reference objects cannot be instantiated without associating the reference object with a reference queue.) You can use the arrival of a phantom reference in a reference queue to trigger some action that you wish to take at the end of an object's lifetime. Because you can't get a strong reference to a phantom reachable object (the get() method always returns null), you won't be able to take any action that requires you to have access to the instance variables of the target. Once you have finished the pre-mortem cleanup actions for a phantom reachable object, you must invoke clear() on the phantom reference objects that refer to it. Invoking clear() on a phantom reference object is the coup de gras for its referent, sending the referent from the phantom reachable state to its final resting place: unreachability.
by narendrn
A lot of "i18N" programs only have to deal with "strings" that need to be localized. For e.g. labels, other text etc.
But what if U need a localized object ?..i.e a double object, a JPEG object etc.
There is a special class in Java "ListResourceBundle" that allows a ResourseBundle to be loaded from a ".class" file.
Read the tutorial below for more info :
http://java.sun.com/docs/books/tutorial/i18n/resbundle/list.html
by narendrn
During "i18n" tasks in my development career, I was amused to see how some locales have the formatting exactly opposite to that of US or UK.
For e.g.
In en_US locale, a number(currency) would look like $9,876,543.21 (separated by comma and a decimal)
But in German, the same number would be written as 9.876.543,21 DM (comma and decimal have opposite meaning !!!)
To furthur add to the confusion, in French, the amount would be written as 9 876 543,21 F (space and comma)
God save us poor mortal developers in understanding these nuances !!!
by narendrn
In most cases, network administrators will configure a firewall to only allow HTTP traffic on the default Web server port, 80. Traffic sent across an HTTP connection is considered relatively safe and, thus, HTTP has become the standard entry protocol to an internal network. Technologies such as SOAP have been designed to provide safe access through a firewall by using HTTP as the transport protocol.
HTTP tunneling is designed mainly for firewall aversion. HTTP tunneling performs protocol encapsulation, by enclosing data packets of one protocol (SOAP, JRMP, etc.) within HTTP Packets. The HTTP packets are then sent across the firewall as normal internet traffic.
SOAP is an excellent example of HTTP-Tunneling in the modern era of distributed computing.
The HTTP tunneling can be thought as a way to use an existing road of communication (HTTP) and create a subprotocol within it to perform specific tasks.
The subprotocol will contain all the information necessary to create an object on the Web Server, invoke the method on that object and return results back to the client.
by narendrn
A compound message contains variable data. In the following list of compound messages, the variable data is in bold:
The disk named MyDisk contains 300 files.
The current balance of account #34-98-222 is $2,745.72.
405,390 people have visited your website since January 1, 1998.
Delete all files older than 120 days.
Such messages are always difficult to localize. Just picking up sub-strings from the properties files won't work and would be very cumbersome. In Java, there is a cool class named "MessageFormat" that can be used in such cases. The following link contains the tutorial:
http://java.sun.com/
by narendrn
Double Buffering is a technique that is used to prevent flicker when drawing onto the screen. The problem stems from the fact that when a new animation frame is rendered, it is desirable to first clear the old frame. This causes a flicker to occur. The basic idea of double buffering is to create a virtual screen out of the user's view. A graphics device could be a screen, printer, file, or memory area. The virtual screen used as the buffer is the primary example of using a memory space as a graphics device. When paint() is called, the clearing and painting of the animation frame can occur on the virtual screen and the resulting rendered image can then be transferred to the real screen immediately upon completion. The cost of double buffering is in memory and CPU consumption. However, this cost is probably unavoidable for complex animations and usually isn't too expensive.
A very good tutorial on how to reduce flicker in Java GUI applications is given at:
http://javaboutique.internet.com/tutorials/
Java_Game_Programming/BildschirmflackernEng.html
Excerpt from the article:
Double buffering means to paint all the things in the paint() method to an offscreen image. If all things that have to be painted, are painted, this image is copied to the applet screen. The method does the following in detail:
- Generates a new offscreen-image by using createImage and stores this image in a instance variable( = generate an empty image)
- Call getGraphics to get graphic context for this image
- Draw everything (including to clear the screen completely) on the offscreen image ( = draw image in the background)
- When finished, copy this image over the existing image on the screen. ( = draw image in the foreground)
This technique means that the picture is already painted before it is copied to the screen. When copying the image to the foreground the old pixels are overlayed by the new ones. There won't be any flickering picture anymore because there is not a millisecond where you see an empty screen!
The only disadvantage of the double buffering is, that it produces a large amount of data and every image is drawn two times (offscreen and when copying to the screen). But in most cases and on a fast computer this is much better than wasting time on finding an other solution!
by narendrn
Actually it depends on what shell U are using...i.e. C shell or Bourne Shell.
There are 2 types of variables:
- Shell variables -- That are local to the shell
- Environment variables -- That are available to all other processes
In C-shell to set a shell variable U type: % set name=value
In bourne shell you can just type: $NAME=value
In C-shell to set an environment variable: % setenv [NAME value]
In bourne shell, U need to export the shell variable, so U type: $ export NAME
A good article explaning the differences is present at:
by narendrn
I have been using JavaCC in a project for parsing Resource files. Anyone who has worked with Parsers before would just love the simplicity and power of JavaCC.
I would strongly recommend using JavaCC to generate any Java parser anyone would ever need. The following links would get U started :)
http://www.engr.mun.ca/~theo/JavaCC-FAQ/javacc-faq.htm
http://www.engr.mun.ca/~theo/JavaCC-Tutorial/ (An excellent tutorial for beginners)
by narendrn
I have often wondered on the "real use" of modules and AL.exe in .NET.
The only use of AL.exe seems to be during i18N process, when we can create satellite assemblies. AL.exe is also useful if U need to link different .netmodules files into a single DLL. But we still need to ship the .netmodule files too along with the DLL !!!
An excellent article discussing this topic can be found at:
http://www.codenotes.com/cnp/baseAction.aspx?cnp=NET030009
by narendrn
Coming from a Java background, I always use to wonder why .NET converts ordinary resource files into satellite assemblies for internationalization.
Why not use the raw resource text files themselves..( as Java uses properties files)
I guess the most imp. advantage U get by converting resources to assemblies is that U can "version and digitally sign" them...i.e. U can give them a version number and also sign them with a private key. So there is a extra security that no one has tampered with the resource files.
by narendrn
Just as reflection can be used to retrieve and interpret metadata, it can
be used to construct and "emit" it. The classes found in the System
.Reflection.Emit namespace allow metadata for new types to be generated
in memory and used at runtime. In fact, you can dynamically create
an entire assembly, its classes and methods, and the IL code behind them.
The "in memory" assembly can then be used by other applications.
A good example and article can be found at :
http://www.codenotes.com/cnp/baseAction.aspx?cnp=NET040002
by narendrn
Here's a list of the most common ports that are in use. A more complete list can be found at :
http://www.iana.org/assignments/port-numbers
0 to 1023
1/tcp: TCP Multiplexor
7/tcp: ECHO protocol
7/udp: ECHO protocol
9/tcp: DISCARD protocol
9/udp: DISCARD protocol
13/tcp: DAYTIME protocol
17/tcp: QOTD (Quote of the Day) protocol
19/tcp: CHARGEN (Character Generator) protocol
19/udp: CHARGEN protocol
20/tcp: FTP (File Transfer Protocol) - data port
21/tcp: FTP - control (command) port
22/tcp: SSH (Secure Shell) - used for secure logins, file transfers (scp, sftp) and port forwarding
23/tcp: Telnet protocol - unencrypted text communications
25/tcp: SMTP (Simple Mail Transfer Protocol) - used for sending E-mails
53/tcp: DNS (Domain Name Server)
53/udp: DNS
67/udp: BOOTP (BootStrap Protocol) server; also used by DHCP (Dynamic Host Configuration Protocol)
68/udp: BOOTP client; also used by DHCP
69/udp: TFTP (Trivial File Transfer Protocol)
70/tcp: Gopher protocol
79/tcp: Finger protocol
80/tcp: HTTP (HyperText Transfer Protocol) - used for transferring web pages
88/tcp: Kerberos - authenticating agent
109/tcp: POP2 (Post Office Protocol version 2) - used for retrieving E-mails
110/tcp: POP3 (Post Office Protocol version 3) - used for retrieving E-mails
113/tcp: ident - old server identification system, still used by IRC servers to identify its users
119/tcp: NNTP (Network News Transfer Protocol) - used for retrieving newsgroups messages
123/udp: NTP (Network Time Protocol) - used for time synchronization
139/tcp: NetBIOS
143/tcp: IMAP4 (Internet Message Access Protocol 4) - used for retrieving E-mails
161/udp: SNMP (Simple Network Management Protocol)
179/tcp: BGP (Border Gateway Protocol)
389/tcp: LDAP (Lightweight Directory Access Protocol)
443/tcp: HTTPS - HTTP over SSL (encrypted transmission)
445/udp: Microsoft-DS SMB - used for file sharing
514/udp: syslog protocol - used for system logging
540/tcp: UUCP (Unix-to-Unix CoPy protocol)
636/tcp: LDAP over SSL (encrypted transmission)
666/tcp: id Software's DOOM multiplayer game played over TCP
993/tcp: IMAP4 over SSL (encrypted transmission)
995/tcp: POP3 over SSL (encrypted transmission)
1024 to 49151
1080/tcp: SOCKS proxy
1352/tcp: IBM Lotus Notes/Domino RCP
1433/tcp: Microsoft SQL database system
1434/tcp: Microsoft SQL Monitor
1434/udp: Microsoft SQL Monitor
1984/tcp: Big Brother - network monitoring tool
3128/tcp: HTTP used by web caches and the default port for the Squid cache
3306/tcp: MySQL database system
3389/tcp: Microsoft Terminal Server (RDP)
5190/tcp: AOL and AOL Instant Messenger
5222/tcp: XMPP/Jabber - client connection
5269/tcp: XMPP/Jabber - server connection
5432/tcp: PostgreSQL database system
6000/tcp: X11 - used for X-windows
6667/tcp: IRC (Internet Relay Chat)
8000/tcp: iRDMI - often mistakenly used instead of port 8080
8080/tcp: HTTP Alternate (http-alt) - used when running a second web server on the same machine (the other is in port 80), for web proxy and caching server, or for running a web server as a non-root user. Default port for Jakarta Tomcat.
8118/tcp: Privoxy web proxy - advertisements-filtering web proxy
49152 to 65535
Unregistered Ports
These are ports that may be in common use, but that are not formally registered with IANA. Where the use conflicts with a registered use, the notation CONFLICT is used.
1337/tcp: WASTE Encrypted File Sharing Program
1521/tcp: Oracle database default listener - CONFLICT with registered use: nCube License Manager
2082/tcp: CPanel's default port - CONFLICT with registered use: Infowave Mobility Server
2086/tcp: Web Host Manager's default port - CONFLICT with registered use: GNUnet
5000/tcp: Universal plug-and-play (UPnP) - Windows network device interoperability; CONFLICT with registered use: commplex-main
5223/tcp: XMPP/Jabber - default port for SSL Client Connection
5800/tcp: VNC remote desktop protocol - for use over HTTP
5900/tcp: VNC remote desktop protocol - regular port
6881/tcp: BitTorrent - port often used
6969/tcp: BitTorrent tracker port - CONFLICT with registered use: acmsoda
27960/udp: (through 27969) id Software's Quake 3 and Quake 3 derived games
31337/tcp: Back Orifice - remote administration tool (often Trojan horse) ("31337" is the "Leet speak" version of "Elite")
by narendrn
In .NET events and delegates both seem to behave almost identically. Actually both of them are closely related. Event is just a added modifier on a delegate.
Another imp. difference is that invoking an event can only be done from within the class that declared the event, whereas a delegate field can be invoked by whoever has access to it.
For more details check out:
http://blog.monstuff.com/archives/000040.html
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
- Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions)
- Consistent (data is either committed or roll back, no ?in-between? case where something has been updated and something hasn?t)
- Isolated (no transaction sees the intermediate results of the current transaction)
- Durable (the values persist if the data had been committed even if the system crashes right after).
by narendrn
"Understand for Java" is a cool tool (also a IDE) that gives us reports showing the cyclomatic complexity of Java classes/methods.
http://www.scitools.com/uj.html
by narendrn
It's a bit trickly to debug the OnStart() method of a service. To debug a service, U need to attach the process to the debugger (that means the process is already started and the OnStart() has been executed). So how do U debug the OnStart() method.
First, the important concept is that U can have more than one service running inside a process i.e. 2 or 3 services can share the same process. (Remember thats why we have 2 classes: ServiceProcessInstaller and ServiceInstaller)
So follow the following steps:
- Make a dummy service under the same process as Ur main service
- Start the dummy service and attach the debugger to the process
- Put a break-point in the OnStart() method of Ur main service.
- Then start Ur main service... The break point will be hit ....Yahooooo.....
by narendrn
When I was first introduced to ASP.NET, I wondered if there was an equivalent to EJB's in .NET.
Well, the answer is YES...
COM+ offer all the same services that a EJB container does. So instead of beans, U write "serviced components".
COM+ services are available on the MTS (Microsoft Transaction Server) plaform and offer the following services:
- Transaction Management
- Object Pooling
- On-Demand (JIT) Object Activation
- Security Management etc.
by narendrn
At first shot, I thought this is absolutely impossible, until I saw this link:
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
FCAPS is the ISO model for network management. It forms the cornerstone of current day network management.
It is an acronym for Faults, Configuration, Accounting, Performance, Security, the categories into which the model breaks the various network management tasks.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
In ADO.NET when I came across the concept of typed data-set, the first question I had on my mind was "WHY?" What are the advantages?
.NET SDK help states the following:
A typed DataSet is a class that derives from a DataSet. As such, it inherits all the methods, events, and properties of a DataSet. Additionally, a typed DataSet provides strongly typed methods, events, and properties. This means you can access tables and columns by name, instead of using collection-based methods. Aside from the improved readability of the code, a typed DataSet also allows the Visual Studio .NET code editor to automatically complete lines as you type.
Additionally, the strongly typed DataSet provides access to values as the correct type at compile time. With a strongly typed DataSet, type mismatch errors are caught when the code is compiled rather than at run time.
--------------------------------------------------
So I understand that one of the advantages of using typed datasets is that you will catch typos in table and column names at compile time not run time as with un-typed data sets. In fact using intellisense eliminates those typos all together..
But during the earliers states of the project. when the database may keep changing according to requirements, U would need to synch the database with the code everytime !!!...Anyway, my personal belief is that all errors relating to column names etc. should be captured during unit-testing. (Or is this impossible in a mega-project and the overhead of manually creating dataset schemas would be justified?)
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
There is a cool trick thru which one can capture the page-output of Aspx pages before it is send to the browser. An excellent article explaining this is at :
http://west-wind.com/weblog/posts/481.aspx
The trick is to override the Page.Render() method, and capture the output in a TextWriter. Then write the same context back to the original textwriter. Sounds confusing..It is a bit :)
Here is the code snippet:
protected override void Render(HtmlTextWriter writer)
{
// *** Write the HTML into this string builder
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hWriter = new HtmlTextWriter(sw);
base.Render(hWriter);
// *** store to a string
string PageResult = sb.ToString();
// *** Write it back to the server
writer.Write(PageResult);
}
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
Quite often, we have to unit-test each and every link on a web site. This could be automated thru a tool called "Link Checker" available at :
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
Whenever we store a hashed password in a file or in the database, then it may be possible for a intruder to get the password using a 'dictionary' attack.
Here's what the MSDN says:
Hashed passwords stored in a text file cannot be used to regenerate the original password, but they are potentially vulnerable to a dictionary attack. In this type of attack, the attacker, after gaining access to the password file, attempts to guess passwords by using software to iteratively hash all words in a large dictionary and compare the generated hashes to the stored hash. If you store hashed passwords by any storage mechanism, you should require your users to choose passwords that are not common words and that contain some numbers and nonalphanumeric characters to help prevent dictionary attacks.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
CVS has done a lot of good to a lot of projects..But there is a new tool that's making waves in the open-source community..A source-control system named 'Subversion' that's touted to replace CVS.
Check out more info at:
http://svnbook.red-bean.com/
by narendrn
With Apple officially declaring that Mac's would move to Intel processors, it brought out an important question in my mind...What would happen to the byte-sex???
Mac's use big-endian format and intel processors always use little-endian format. So how will applications on Mac behave if the Intel processors are used?
For more info on byte-sex, check out these links below:
http://www.cs.umass.edu/~verts/cs32/endian.html
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
by narendrn
The first one performs a deep copy of the array, the second one is shallow.
Trending After Hours posts
Sort by Trending