Thursday, October 10, 2013

The Java class library and language from a C# point of view.

Previously I spoke about my experiences installing Java and using Eclipse.  This time I'll look at my positives and negatives with the actual Java language and class library.  Once again I'm coming the perspective of a C# programmer.

My focus, at least initially, is working on client side (desktop) applications as opposed to server based enterprise systems.  When learning a language / environment I find it very useful to be able to easily write code that gives rapid visual feedback that indicates to me that what I'm doing is actually correct.  I feel choosing JSE as opposed to JEE allows me to more easily do this.

Basic multi-threading

I certainly haven't delved into the depths of the threading library in Java however the simplicity of the Runnable interface is very nice.  You simply implement the Runnable interfaces Run() method on a class that requires another thread of execution.

Then create an instance of the Thread class, passing an instance of the Runnable class to the constructor.  Finally, call start() on the thread instance to begin thread execution.  Here's an example:


public class AppWindow extends Canvas implements Runnable
{
 private Thread _thread;

 @Override
 public void run()
 {
  // Do work on another thread here
 }

 public void start()
 {
  _thread=new Thread(this);
  _thread.start();
 }
 
 public static void main(String[] args) {
  
  AppWindow appWindow = new AppWindow();
  
  appWindow.start();
 }
}

Of course the real "fun" with threading depends on what you actually do in the run() method.

For example it's essential to avoid a situation where two (or more) threads read the same shared value, modify the value in some way and then update the shared value.  This may not directly cause your application to crash, however it causes extremely confusing exceptions / behaviours.  This is called a race condition and is a well known problem in concurrent programming.

The Java synchronized keyword is useful to ensure only one thread can run a block of code or a method at a time (serialized access) but this also can create a bottleneck when threads have to wait for a synchronized code to complete.  In this way the Synchronized keyword is semantically identical to the c# lock keyword, although lock cannot be used on methods (a  MethodImpl attribute is required).

I've also come across the AtomicXXXX classes such as AtomicBoolean, AtomicInteger that give you a safe way to modify some the atomic variable in multi-threaded code.  Using an Atomic variable avoids the need for the Synchronized keyword and its associated bottleneck issue.

The methods on these classes such as compareAndSet() are guaranteed to complete before any other thread can interrupt and possibly modify the same variable.  For example you could use one Atomic variable as a lightweight and safe way to count the number of threads currently executing some code and make a decision based on that number.  NB: These classes are not radioactive in any way ;), the word "atomic" in this context means "all or nothing".

Multi-dimensional arrays

Java does support arrays of arrays (jagged arrays) however it does not provide a built-in C# style array [,].  However this hasn't been an issue for me because in Java you can declare an array of arrays by specifying the lengths of all dimensions at in the declaration:

int [][] twoDArray = new int[10][10]; 

In C# you'd have to write:

int [][] twoDArray = new int[10][];
for(int i=0;i<10;i++) twoDArray[i]=new int[10];

Of course multidimensional C# arrays using [ , ] do make declaration easier, however in my experience they can be slower than jagged arrays for an application doing heavy array accessing.

In fact, in an informal performance test (I may need to create another post with details this test) Java jagged arrays were a little faster in access than C# jagged arrays and clearly faster than C# [ , ] style arrays.

No operator overloading

Java does not support custom operator overloading (except built-in string concatenation +). As a result much of my Vector manipulation code in Java looks like:

Vec2D a = Vec2D.add(b.multiply(-1), c.multiply(0.5));
d.multiply(a);

With operator overloading the following would be possible:

Vec2D a = (b* -1) + (c*0.5);
d *= a;

Now there are heated views for both sides on value of operator overloading.   In all my time using C# I've only needed operator overloading on quite specific but very applicable situations such as with geometrical Vector and Matrix classes.  Moreover, the increase in clarity of the above code cannot be ignored. 

In my opinion redefining + - * / for a class such as Vector has no real drawbacks.  The most common concern is that overloaded operators hide the actual code and therefore make it easier to write poorly performing code.  However a decently written overloaded operator should be identical to the longhand approach in terms of performance.  The programmer always has the choice of using the longhand approach anyway.        

I personally can't remember ever redefining any further operators than the 4 mentioned above in C#.  Adding the ability to overload at least these operators to Java is long overdue. Limiting it to these 4 operators is also likely to reduce the occurrence of obscure or misleading operator overloading.

Overriding methods

In Java, to override a method of a base class in the sub class you just add the @Override annotation above your overriding method.  No need to check that the base class method allows it.  This is because methods are virtual by default.

In C# you must first ensure that the method you are overriding is either virtual or abstract and then add the override keyword as part of the method declaration.  Methods are non-virtual by default in C#.

For reasons of clarity I prefer the C# explicit style where the programmer is forced to think about which methods should be overridable.  If a programmer does not think about this at all (eg. leaves all methods as non-virtual), performance is still good as there is no dynamic binding required to call to these methods and they can be in-lined by the compiler giving the associated benefits.

Making a method overridable often requires careful thought about how this can change the behaviour of other class methods that may depend on it, as well as the overall usage of the class itself.  So C# leans towards safety here.  Classes are not sealed by default however, so this seems a bit inconsistent.

In Java if the programmer does not consider which methods should be overridable, they are, by default, all overridable and so require dynamic binding .  The programmer can explicitly add the final modifier to a method to stop anyone overriding it.  In the past this also has the side benefit of telling the Java runtime that the method does not need dynamic binding and can be inlined if beneficial.

So then, coming from C#, I might be tempted to add final to all of my base class methods.  However the modern Java runtime can determine methods that are not being overriden and will treat treat them like a final method, with the associated performance benefits.

Therefore the rule here is to use the final keyword where it makes sense from in the context of your design, ie you specifically want to stop someone overriding for correctness / clarity of usage reasons.  Do not use final for performance reasons as it obscures your intent to another programmer.  The runtime is intelligent enough to do this for you.




Monday, October 7, 2013

Java and Eclipse from a .NET developers perspective.

I recently installed Eclipse (Kepler) and Java 7 SE to expand and brush up on my Java knowledge.  I last worked with Java back in in the 90's during my Computer Science education so you could say it's been a while.

For the past decade or so I've been working with .NET almost exclusively, so I'm hoping this journey out from under the Microsoft shadow will be most informative.    Here are my experiences so far:

Finding the right downloads.

It was slightly confusing at the Eclipse download page as to which download I really needed.  I knew I wanted to focus on desktop applications initially so that means Java Standard Edtion (JSE) rather than Java Enterprise Edtion (JEE).

However there is an "Eclipse Standard" download as well as an "Eclipse for Java Developers" download and the descriptions of both did not clarly differentiate which would be better for me, based on my needs. However Eclipse Standard had 6 times as many downloads and was about 50MB larger so I decided to ho with that.

After reading the Eclipse forums, I understand that Eclipse is best seen as a container for various packages, and that it is the packages that provide the most functionality.  Therefore don't get too caught up about the specific initial download.  You can just add and remove packages later.

The JRE and JDK

My system already had both the 32 bit and 64 bit Java Run-time Environment (JRE) installed and up to date. So nothing further to do here.

However Eclipse doesn't actually include the Java Development Kit (JDK). The JDK can be downloaded separately from Oracle.  Before you download it, be aware that it is not actually required to create and run Java programs because the Eclipse installation includes the Java compiler.

I downloaded the JDK anyway as it contains the source code for the system class libraries as well as additional tools that build and version control systems (Maven etc) rely on.  To this point it looks like Eclipse only cares that the JRE is installed, it appears to have no direct dependency on the JDK.

Installing Eclipse


The Eclipse download was a zip file rather than an installer so it's up to you where you put it on your system.  I have a base development directory containing subdirectories for my .NET projects and other languages.  So I just created a Java / Eclipse directory under this and unzipped Eclipse here.  In this directory is the Eclipse.exe executable, which can be run directly or shortcut/s to it created and placed wherever you find convenient.

On first running Eclipse it asked me to open an existing workspace or create a new one.  So I created a new workspace directory: Java / Workspace.  Don't know if this is the best structure but it works for me so far and allows me to easily include Java in my backup procedure.

Initially I thought that a Workspace was a more general concept than the 'Solution' in .NET and so I created one Workspace under which all my Java projects are then created.

Right now however I feel that a Workspace is closer to a Solution than I first thought.  For example: Eclipse defaults to showing all errors and warnings for all projects in the curent workspace. That means if you have unrelated projects under the one workspace, by default, you see the warnings and errors for those projects too.

Also, the Eclipse 'package explorer' shows all projects under the workspace, although you can easily expand and collapse these as required.  I think I may need to review my workspace structure in future.

First Impressions of Eclipse

In short, I've been very pleasantly surprised.  Here's what I've found most impressive:

  • A nice range of built-in refactorings. I particularly like the "no context switch" rename refactoring that I use daily. 
  • Powerful code navigation and search tools such as find references, write/read accesses, implementors etc, once again all built-in.
  • Hot Code Replace.  Run your application, make changes to source code within methods/functions while running, save and watch the changes immediately take effect in the running application.  This is what "fast feedback" is all about. 
  • Keyword searchable options/preferences.  Why is this not mandatory in all large or complex applications? This has been an enormous help to avoid minutes at a time hunting around for some obscure setting.
  • Key shortcut configurability.  Although I'm trying to learn Eclipse key shortcuts, it is happy to let me change the key used for any command I require. 
  • The Javadoc context window that provides documentation on the system classes and can focused and expanded unlike a simple tooltip.  
  • Solid and flexible window layout control.  I can move and dock/anchor windows exactly where I want them. 
  • Solid multi-monitor support.  Tool and navigation windows stay exactly where I want them and can have layours for different usage contexts such as when debugging, editing and so on.
  • Adding new packages has been simple using the IDE integrated online marketplace. 


Things that could be better:

  • I like a darker background syntax highlighting scheme for the text editing window.  This is certainly possible, however it is much harder to change the color scheme used for the rest of the IDE (ie tool windows, package explorer etc).   Having a dark background editor window while the rest of the IDE is bright white is hard on the eyes. (It looks like Eclipse has recently moved to a CSS like styling system that I believe gives control over this, with a little tinkering).
  • Content assist (ie: Intellisense) gives useful contextual feedback and information.  However it seems to become confused and stops working in certain java files. I found that closing the file and re-opening it brings it back again though. 
  • There seems to be a bug in Kepler that means an exception window is not displayed for runtime exceptions.  This means I have to look at the Debug window, or the Output window for information on what went wrong.  Hopefully this is fixed soon.  
  • While debugging it is not possible to "Jump to a statement" (change the current instruction pointer) as I could in Visual Studio.  You can return to the start of the current function though.


Comparison to Visual Studio.

After years of working with Visual Studio up to version 2010 I have become increasingly frustrated with the view that Visual Studio is by far the best IDE available.

Don't get me wrong, it is a servicable IDE with a powerful debugger, good visual designers and is much more productive than a text editor, once you learn its quirks.  However it is also patently obvious that without third party extensions such as Resharper (and others) it is, at best, nothing special, and at worst, over-priced and lacking usability.

Resharper is a powerful aid, that is if you have at least a 4+ Core, 16GB RAM+  machine.

Right now I can't afford to upgrade my current Dual Core 3.3 Ghz, 8GB RAM Windows 7 64bit PC. Resharper brings Visual Studio almost to a standstill on this machine.  Background compilation can be turned off, but Resharper loses much of its power without it, so whats the point in spending $100 for it.

While I realise Eclipse is probably not doing background compilation, in Eclipse I can at least have good refactoring support and a snappy responsive IDE at the same time without upgrading my perfectly good current PC.

Over the years I've tried fixing frustrations I've had with Visual Studio myself.  I've written extensions, macros, configurations etc, but have either found the core issue can't be fixed or the time and effort required to do it is excessive.

A common refrain from fellow .NET developers was, "oh, I've heard that they fixed that in the new VS 20XX)".  Sadly, it very rarely was. Of course each new version introduces more flashy visual designer support for Silverlight, WPF, ASP.NET MVC etc.  In my opinion they need to  focus on the basics of usability again instead of flashy new features, but I know that's not going to happen.

Finally

So that's it for now, thanks for reading.

My primary goal here was to give an overview of my first impressions of Eclipse and Java (as it stands in October 2013) from the point of view of a (possibly cynical) .NET developer.  Hopefully it was informative?  I also feel there are a lot of opinions and views regarding Java (both in my head and in the wider .NET community) that I intend to examine for basis in reality.

It's funny, but not only has the experience been pretty smooth and painless so far,  it's making aspects of Visual Studio and .NET look very ordinary in comparison.

I've focused on Eclipse in this post, so perhaps next time I'll look at Java itself.