Monday, February 06, 2006
One Thread to rule them all
A small diversion to Threads in Java
Now in Java the Runnable interface is used to create threads. Runnable contains a single method run() which needs to be implemented.
<code>
public class MyThread implements Runnable {
public void run() {
//do some task
}
}
</code>
To execute the above as a separate thread you need to call the start method of the Thread class. The Thread class can accept a Runnable instance
<code>
new Thread(new MyThread()).start()
</code>
start() internally performs some housekeeping to actually create the new thread. After performing the necessary operations, Runnable.run() is called.
Back to our UI Application.
What is done is a simple event queue is built for handling all non-ui tasks. Which internally contains a Queue and a single thread.
<code>
public class Worker implements Runnable {
private Queue queue;
private boolean running;
private Worker INSTANCE = new Worker();
private Worker() {
new Thread(this).start();
}
public static Worker getInstance() {
return INSTANCE;
}
public void run() {
if(!running) {
running = true;
while(true) {
if( queue.peek() ) {
Runnable runnable = queue.pop();
runnable.run();
}
}
}
public void addRunnable(Runnable runnable) {
queue.push(runnable);
}
}
</code>
I have just given a basic skeleton here and left out the most important part of synchronizing the class. The running boolean was added to prevent new Thread(Worker.getInstance()).start(). You guys see any more errors? Threads are one of my primary weaknesses which I hope to rectify by learning about the new Java 5 Concurrency features.
For small tasks it is more efficient to use a Worker like this which internally doesn't create a new Thread for each task and re-uses a Thread or even a thread pool. This is because the start() method does quite a bit internally.
In Swing it's suggested to use a SwingWorker class which does something similar. Also Java 5 (Tiger) has added a new SwingWorker class which is additionally Generic.
The generic question now. Have you guys come across any similar stuff in other languages? Java has had good support for threading since the early days and now in Java 5 this has been greatly enhanced. What about other languages? C++, C#. And anyone have info about dynamic languages like Lisp, Python etc?
Saturday, February 04, 2006
Refactoring enhanced
Monday, January 30, 2006
Re: Google China
I wish Google had taken a stand and said no to the Chinese Government, but ultimately its their company and they have a right to do what they wish with their search results.
Dinesh.
Friday, January 27, 2006
Google China
You must have heard about Google sensoring their search results to meet China's demands. What dyou think? Once a company goes public, it takes on many more responsibilities. Although an admirable motto - Do No Evil - it was always going to be hard to stick to that when you have to satisfy shareholders. Growth in revenues and profits becomes your number one goal. That is automatically seen as 'evil'. Which is another interesting point... you think a super successful company can ever be seen in a favorable light?
Thursday, January 26, 2006
Re: Another greasemonkey script....
// ==UserScript==
// @name Google Analytics Detector
// @namespace http://codeword.blogspot.com
// @description Detects if a page uses Google Analytics
// @include *
// ==/UserScript==
var URL = "http://www.google-analytics.com/urchin.js";
var TRACKER = "urchinTracker()";
var scripts = document.getElementsByTagName( "script" );
var refPresent = false, codePresent = false, log = false;
for ( var i = 0; i < scripts.length; ++i ) {
var script = scripts[ i ];
// Check reference if not already found
if ( !refPresent ) {
var ref = script.src;
if ( ref != null ) {
refPresent = ( ref.search( URL ) != -1 );
if( log )
GM_log( "Tested ref: " + ref + " Result: " + refPresent );
}
}
// Check code if not already found
if ( !codePresent ) {
var code = script.innerHTML;
if ( code != null ) {
codePresent = ( code.search( TRACKER ) != -1 );
if( log )
GM_log( "Tested code: " + code + " Result: " + codePresent );
}
}
if ( refPresent && codePresent ) {
var logo = document.createElement("div");
logo.id = "logo";
logo.innerHTML = '<div style="position: absolute; left: 0px; top: 0px;' +
'border-bottom: 1px solid #000000; margin-bottom: 5px; ' +
'font-size: small; background-color: #000000; z-index: 100;' +
'color: #ffffff; width:200px; opacity: .75;"><p style="margin: 2px 0 1px 0;"> ' +
'<b>Google Analytics enabled</b>' +
'</p></div>';
document.body.insertBefore( logo, document.body.firstChild );
window.setTimeout(
function() {
var logo = document.getElementById( "logo" );
if ( logo ) {
logo.parentNode.removeChild( logo );
}
}
, 5000 );
return;
}
}
Re: Another greasemonkey script....
// ==UserScript==
// @name Google Analytics Detector
// @namespace http://codeword.blogspot.com
// @description Detects if a page uses Google Analytics
// @include *
// ==/UserScript==
var scripts = document.getElementsByTagName( "script" );
var refPresent = false, codePresent = false;
for ( var i = 0; i < scripts.length; ++i ) {
var script = scripts[ i ];
// Check reference if not already found
if ( !refPresent ) {
var ref = script.src;
if ( ref != null ) {
var URL = "http://www.google-analytics.com/urchin.js";
refPresent = ( ref.search( URL ) != -1 );
GM_log( "Tested ref: " + ref + " Result: " + refPresent );
}
}
// Check code if not already found
if ( !codePresent ) {
var code = script.innerHTML;
if ( code != null ) {
var ACCT = "_uacct";
var TRACKER = "urchinTracker()";
codePresent = ( ( code.search( ACCT ) != -1 ) && ( code.search( TRACKER ) != -1 ) );
GM_log( "Tested code: " + code + " Result: " + codePresent );
}
}
}
if ( refPresent && codePresent ) {
alert( "This smart bastard is using Google Analytics" );
}
Save as analyticsDetector.user.js, open in Firefox and then "Install This User Script..."
Couple things... Besides the code snippet Rahul posted, there is also an external js file that is referenced (http://www.google-analytics.com/urchin.js). I check that both code as well as reference are present. Also in the code, I think "_udn" is optional. It's there on slashdot, but not on codeword, so I don't check for that. Didn't test this very much. Just on codeword, slashdot (detected) and yahoo, microsoft (undetected).
Any improvements?
Wednesday, January 25, 2006
Introduction to Great Design
Also check This is Broken - "A project to make businesses more aware of their customer experience, and how to fix it". It's a nice site with daily postings on design mistakes seen everywhere.
Tuesday, January 24, 2006
Another greasemonkey script....
<idea>
Quite a few sites use the Google Analytics service. Sites insert javascript code like -
<script type="text/javascript">
_uacct = "UA-32013-5";
_udn = "slashdot.org";
urchinTracker();
</script>
(The above code is from slashdot ).
A script could be written which shows a simple notification whenever a site visited ; contains Google Analytics javascript.
</idea>
Any takers??
Monday, January 23, 2006
Some free books....
Basically I got a few books at http://www.freetechbooks.com. You guys could also get something on your topic.
Wednesday, January 18, 2006
Book Reviews
Trying to gauge how good a book before you buy it can be a pretty hard task! Money doesn't exactly grow on trees ;o) One site I have found useful and insanely accurate in terms of their book reviews is www.accu.org. This is primarily a C++ site but they also give reviews for C# and Java.
Before buying any book, I usually run a search through there to see how its rated.
Dinesh.
Modern C++ Design
I would really recommend you to try out "Modern C++ Design by Andrei
Alexandrescu". It is a fantastic book delving deep into C++ Template
Techniques. Its not something a novice can read, but yet if you are
comfortable with C++ templates, then you should definitely give it a
shot!
He opens your eyes to a lot of interesting techniques and in the process
also unravels "Loki", the library (written by him) which implements all
of the techniques!
Policy class, local classes, typelists - the list just goes on, its all
there!! He shows what you can do with even the most simple template
classes viz :-
template<bool>
struct CompileTimeChecker
{
CompileTimeChecker(...) {}
};
template<> struct CompileTimeChecker<false> {};
This relatively simple struct can achieve compile time assertions for
you!
Read it! Its worth it!
Dinesh.
Monday, January 09, 2006
Use that extra bit of vegetable oil at home
This is really one of the most hilarious things I've ever seen -
http://www.tomshardware.com/2006/01/09/strip_out_the_fans/
Keep it cool ;o)
Dinesh.
Friday, December 16, 2005
Singleton design pattern
A few advantages of Singleton we came up with were..
Singletons can be subclassed. And preferably used with Factories or Registries.
Another subtle difference was usage. When you have a singleton, you get back a class instance on which you then perform operations. Like..
Singleton singleton = Singleton.getInstance();
singleton.doSomething();
singleton.doSomethingMore();
Compare this to ..
Math.cos(..);
Math.round(..);
The Singleton is just more correct because it allows to think in terms of a type and its behaviour and limits the instances. The static method form does not exhibit the same level of coherent behaviour. It's not the most cleanest distinction but I guess you know what I mean.
I was in the mood to read more on this and stumbled on an article on Javaworld - Simply Singleton. Definitely worth a read.
...which reminded me of a basic feature of Singletons we missed - controlled instance creation
Thursday, December 15, 2005
RE: Free UML Tool?
Revo, Most of the reverse engineering software's that can be found for
UML are not freely available. There's EclipseUML @
http://www.omondo.com/ that you can try. The free version does not have
reverse engineering capabilities and the Enterprise Edition has a 30-day
evaluation limit.
There are others too, but more or less the story stays the same, go to -
http://eclipse-plugins.2y.net/eclipse/plugins.jsp?category=UML
If you do decide to evaluate EclipseUML (which is a plug-in for Eclipse)
make sure you have the dependencies of the EMF, UML and GEF packages
right.
Dinesh.
Sunday, December 11, 2005
Free UML Tool?
Preferably the tool should be light on resources.
Monday, November 21, 2005
Ajax & PHP without using the XmlHttpRequest Object
http://www.phpit.net/article/ajax-php-without-xmlhttprequest/
Sunday, November 20, 2005
Re: Generics in Java
This generics thread is just going to get more and more complicated. In Java, the compiler checks all* generic code at compilation time.
So if I say,
List<Integer> ints = new ArrayList<Integer>();
ints.add("a String"); //Oops... compilation error
But the bytecode generated will be similar to that generated pre Java 5 with casts inserted by the compiler.
Now there are some cases where you have no option but to make an unchecked cast to make code work. In such cases the compiler is not sure that the code/cast is wrong. So compilation is allowed with an unchecked cast warning.
class UncheckedCast<E> {
private E[] arr;
public void meth() {
arr = (E[])new Object[5]; // unchecked cast
}
}
Also....
<excerpt>
Generics for Java are accompanied by a cast-iron guarantee: no cast inserted by erasure will fail, so long as there are no unchecked warnings. The above illustrates the converse: if there are unchecked warnings, then casts inserted by erasure may fail.
</excerpt>
"? extends X" and "? super Y" are Wildcards. They are used to increase the range of Types that can be put in or removed from Generic methods/classes. This is a hack to reduce the effects of Erasure. I do not think this will be there in C++ or C#.
A slight diversion..
Does C# too have primitives? I have come across a few instances where having primitives in Java has hurt. Primitives requires having to make all special conversions and stuff. I suppose SmallTalk, Ruby are pure-OOPs wrt this.
I haven't delved too deep into how C# (.NET) has handled these situations. But I think there will be differences since the two implementations are different... no erasure, so type info is preserved. There is something called a constraint which basically allows you to declare an interface you want the parameter type to implement or inherit from some base class or specify that it has a default constructor...
Java too supports Constraints and its called Bounds. So the example Mohnish mentioned for max can be written in Java as...
public static <T extends Comparable<T>> T max (T a, T b) {
if( a.compareTo(b) < 0 )
return b;
return a;
}
Btw Comparable is an interface which takes a generic type T.
I don't remember reading about Bounds/Constraints in C++... How is a similar thing done?
About the C# Constraints...
where T : new() T must have a no-parameter constructor
Java doesn't have anything similar. It seems to be an interesting constraint which should be useful in creating types of T even though the Type T is only known at runtime.
where T : class T must be reference type (a class)
where T : class_name T may be either class_name or one of its sub-classes (or is below class_name in the inheritance hierarchy)
Could you give an example of the usage of the above Constraints. To clarify; the first constraint only takes T, and the second takes T or its sub-class.
Saturday, November 19, 2005
Re: Generics in Java
But having said this, I think it's important to take some perspective. Most Java programmers are 'consumers' of APIs. Using these generic classes isn't very difficult. It actually makes better type guarantees and is more natural to use (no messing with casts). The complications of generics only occur when you write generic APIs - this burden is borne by the 'producers'. This is in a way good since there are generally more consumers than producers, so fewer people have to understand the complexities of covariants, contravariants and invariants etc... When was the last time you wrote a generic class?
The other thing is that unlike C++, in Java all the checks (as you said) are done at runtime. Add to this the fact that it has a unified type system where all types (except primitives) inherit from Object makes it even more complicated. Both these are the reason for things like "? extends X" and "? super Y". You don't find these in C++ templates (Atleast I haven't seen them - can someone confirm?). Everything is checked at compile time so the compiler will warn you if the parameter types don't have expected methods. There's no need to specify that you want parameter types to extend or be the super type of some class.
I haven't delved too deep into how C# (.NET) has handled these situations. But I think there will be differences since the two implementations are different... no erasure, so type info is preserved. There is something called a constraint which basically allows you to declare an interface you want the parameter type to implement or inherit from some base class or specify that it has a default construtor...
public T genericMethod<T>() where T : constraint
where constraints can be...
where T : struct T must be a value type (a struct)
where T : class T must be reference type (a class)
where T : new() T must have a no-parameter constructor
where T : class_name T may be either class_name or one of its
sub-classes (or is below class_name
in the inheritance hierarchy)
where T : interface_name T must implement the specified interface
Why the need for constraints? Consider this simple ex.
public static T Max<T>( T a, T b )
{
if ( a.CompareTo( b ) < 0 )
return a;
return b;
}
This will fail at compile time. The compiler doesn't know whether a and b support the CompareTo method. There needs to be a way to limit what the parameter types can be... some constraint.
public static T Max<T>( T a, T b ) where T : IComparable
{
if ( a.CompareTo( b ) < 0 )
return a;
return b;
}
This satiates the compiler since it will make sure that when you call this method, the types of objects used as parameters implement Icomparable.
This seems like a bit of a sidetrack. I'll try and read up some more on C# generics and post any differences/similarities to covariants, contravariants and invariants.
Friday, November 18, 2005
Re: codeWord changes??
We could also publish codeWord in a few blog directories.
Both are fine by me. Anybody have objections?