Tuesday, January 29, 2008

Google Interview Questions - Part 9

Q1: How you would tweak bits in C to find out if a machine’s stack grows up or down in memory?

Q2: There are 8 stones which are similar except one which is heavier than the others. To find it, you are given a pan balance. What is the minimal number of weighing needed to find out the heaviest stone ?

Q3: N threads .. n resources .. what protocol do you use to ensure no deadlocks occur?


Here are the answers:


A1: Instantiate a local variable. Call another function with a local. Look at the address of that function and then compare. If the function's local is higher, the stack grows away from address location 0; if the function's local is lower, the stack grows towards address location 0.

A2: Divide the stones into sets like (3,3,2). Use pan to weigh (3,3). If the pan is remains balanced, the heavier is in the remaining (2). use pan again to find which is heavy from (2). (Total pan use 2) If the pan does not remain balanced when weighing (3,3), pick the set of stones that outweigh other. Divide it into (1,1,1). use pan to weigh first two. It it remains balanced, the remaining stone is the heavier, otherwise the one outweighing other is heavier(total pan use 2)

A3:

  • Avoiding Deadlocks with Lock Leveling, each thread would have different level, thread with high level would be able to lock thread with lower level but not contrary.
  • Avoid acquiring more then one lock at a time.
  • Acquire the lock always in the same order.
  • Shrink synchronized blocks.

Thursday, January 24, 2008

Most Popular Developers Interview Question

This is one of the most popular developers interview question I know,

I had been asked about this question so many times.



The question is about the singleton design pattern, how to ensure a single instance of singleton object.



This answer is wrong:



public MySingleton getInstance() {

if (instance==null) {

instance = new MySingleton();

}

return instance;

}



This is because if two thread would call getInstance the same time then they may both enter the if statement before instance was initialized.



Another answer for this question is to initialize instance in the creation of the class.



private static final MySingleton instance = new MySingleton();



but if the classloader is not lazy then this class would be initialized even if no one use it.



A good solution is to initalize it in a static section of the class



static {

instance = new MySingleton();

}



this code would only be called when someone create an instance of the class and two threads can't enter the same time the static section.



Another bad solution is to write



public synchronize MySingleton getInstance() {
if (instance==null) {
instance = new MySingleton();
}
return instance;
}



This is not good solution since each time someone would get instance it would synchronize the call this would decrease the performance.



So a more sophisticated good solution is:



public synchronize MySingleton getInstance() {

if (instance==null) {

synchronize {

if (instnace == null) {

instance = new MySingleton();

}

}

return instance;

}



in this case two threads can enter the first if statement in the first call but then only one of them would get into the second if since the synchronize keyword, this would create only one instance, and also this would create in lazy when the singleton is first access.



Be prepared to be asked about this question in your next interview.

Spring vs. EJB 3

This article would overview the differences between Spring Framework and EJB 3

EJB 3.0

  • EJB 3.0 is a specification.
  • EJB is an architecture
  • The EJB 3.0 framework is a standard framework defined by the Java Community Process (JCP) and supported by all major J2EE vendors. Open source and commercial implementations of pre-release EJB 3.0 specifications are already available .

Spring Framework
  • Spring is an implementation.
  • Spring is application framework
  • The Spring framework is a popular but non-standard open source framework. It is primarily developed by and controlled by Interface21 Inc. Spring can work standalone or with existing application servers.

EJB 3.0 Advantages
  • EJB 3.0 specification horroble old entity beans have been replaced with the JPA
  • Deal with transactions and both succeed modularizing this functionality in a way that it doesn't clutter business logic
  • Tune the transaction propagation levels via annotations
  • Support state management via stateful session beans,
  • Support injection of primitive types, allows injecting EJB's
  • Supports AOP using interceptors
  • Brings a basic implementation of component management
Spring Framework Advantages
  • Integrates with many popular persistence frameworks including JDBC, Hibernate, JDO, iBatis and JPA.
  • Transaction demarcation, propagation, and isolation are all declared through its AOP.
  • Support state management via prototype beans and also request, session, and global session scoping
  • Support injection of any type, allows injection of any domain objects using the features of AspectJ
  • Suppotrs AOP by tightly integrating with AspectJ with all of it's features
  • Spring 2.0 offers a lot more power and customization, but the use of AspectJ actually makes the hard to learn

Spring Framework Disadvantages

  • The idea of annotations was to stop work with XML - Deploymenet Descriptor files which were in EJB 2.1, but Spring encourage a lot the use of XML for dependency injection
  • Refresh the Spring load data is impossible, if you change something in the configuration you need to restart the Application Server.

You can integrate Spring and EJB 3 technologies to take advantage of their relative strengths and weaknesses, In Spring and EJB 3 there are a lot of duplication in the compoments you can choose the best of this technologies to use in you application.


Friday, January 18, 2008

Writing Cluster Application

Here is a checklist of things that need to be done to write good application which would work in Cluster enviroemnt

  • When accessing the cluster from outside using HTTP or RMI verify that access to the cluster is done throught load balancer, this can be either software or hardware load balancer.
  • Consider using 'Optimistic Locking' or 'Pemisitic Locking' if two or more clients may update the same row in the databse at the same time
  • If you want to cache data all over the cluster and not on a single server then don't use Singleton, you would need to user Cache framework such as GigaSpaces or OSCacheor JCache etc', this solution is good mainly for read only data or data which is mostly read.
  • In many application servers you can configure your MDB if it would run on a single server or on several servers.
  • Avoid reading files/writing to files in the code, Since you may run on different hosts in the cluster and the files may not exists on the current host which you are running
  • Use Synchronize where two threads may access the same data at the same time, This problem can also occure on non cluster system.

Please comment if you have other issues which are missing.

Top Buzzwords which make you Expert

Here is a top five buzzwords which developer needs to know in order to make himself an expert

  1. Scalability - Means that the application can handle a growing amount of work in a graceful manner, Usage Example: "I don't think that this system is scalable, A raise in my salary might encourage me to make it scalable"
  2. Robustness - Means that the application can withstand stress and can continue to operate despite ourside or inside errors, Usgae Example "This application is robustness, One time I explode it with Dynamic and it continued to run"
  3. High Availability - Means that the application ensures a certain amount of operational continuty during a given period, Usage Example: "This application high availability stinks, we need to build a cluster of servers to make it high avilable"
  4. Interoperability - Means that the applications can exchange data in commonn set of exchange format. Example: "We should expose the application service with Web Services this would make our application interoperabale"
  5. Portability - Means that the application can run on a different operating system, Example: "In a team meating I told my boss that we should write a portable application beacuse the application needs to run also in Unix, He promote me to team leader"

Thursday, January 17, 2008

Sun agrees to pay $1b for MySQL

Sun Microsystems Inc., the third-largest maker of server computers, agreed to buy software company MySQL AB for about $1 billion.

MySQL is the world's most popular open source database, over 100 million copies of its software downloaded or distributed throughout its history, It is mainly used by web sites and it is used also by Google Inc.

What is the interest of Sun to buy MySQL, well Sun unlike IBM/Oracle/Microsoft doesn't have it's own Database, Sun has its own Application Server and this would create a more complete product solution which would be supply by Sun.
The profits for Sun will come from the support for MySQL installations.

The question now when Sun would be bought and by who?

Wednesday, January 16, 2008

Oracle to Pay $8.5 Billion for BEA

Another acquestion by Oracle, this company just swallow all the other competitions.

The big question what is now what would be now with BEA WebLogic application server? Since Oracle has it's own application server 10g, would they stop to develop it? My guess is that they will continue to support old 10g customers and would offer new customer BEA WebLogic application server.

Oracle profits are just continue to grow and this cause Oralce competitiors to afraid, Now that there are now only two major J2EE Application - IBM and Oracle it would be intrest to see what would be the next acqusiton

Google Interview Questions Part 8

This questions are a bit tricky, lets see if you can solve it.




First question:

        1
       1 1
       2 1
    1 2 1 1
  1 1 1 2 2 1

What is the next number?

Second question:


What number comes next in the sequence: 10, 9, 60, 90, 70, 66, ?

A) 96
B) 1000000000000000000000000000000000\
0000000000000000000000000000000000\
000000000000000000000000000000000
C) Either of the above
D) None of the above




And here are the answers:

First question answer is:

one
one one (Since the previous line has one time one number)
two ones (Since the previous line has two time one number)
one two one one
one one one two two ones

So the next line answer is 3 1 2 2 1 1


Second question answer is:

ten, nine, sixty, ninety, seventy, sixty-six,

Each number has one letter more than the previous number, ten has 3 letters, nine has 4 letters etc'

Since "sixty-six" has 8 letters the next number need to have 9 letters which is
ninety-six

You can find more questions here:

Google Interview Questions Part 1
Google Interview Questions Part 2
Google Interview Questions Part 3
Google Interview Questions Part 4
Google Interview Questions Part 5
Google Interview Questions Part 6
Google Interview Questions Part 7

GWT vs. Flex

This article would compare Google GWT (Google Web Toolkit) and Adobe Flex 2 and would describe the advantages and disadvantages of each of these technologies.
This two technologies are both Rich Internet Application (RIA) frameworks.

GWT Advantages:

  • Doesn't require plug in installation on the client side
  • GWT doesn't require the user to know JavaScript since the code is written in Java
  • GWT doesn't cost money since it is Open Source.
  • Changes in the Client side are immediately shown on the browser by using refresh, no need to restart the server.
  • GWT can be easily debugged in hosted mode.
  • There is compatible between different web browsers.

GWT Disadvantages:

  • The html and JavaScript code which GWT generates is pretty heavy and not necessary fully optimized.
  • GWT doesn't come out of the box with all the possible widgets, there is a need to use extra components

Flex Advantages:

  • The UI looks nicer then plain HTML/JavaScript code, It contains huge amount of animations, widgets etc'
  • Compatible between different web browsers
  • Flex 2 SDK and Flex Builder 2 for Education are both free
  • Google can index SWF files

Flex Disadvantages:

  • It requires plug in installation on the client side , however this may not be disadvantage since Adobe claims that Flash is installed on more then 99% percent of users.
  • Flex Builder 2 costs some money






Friday, January 11, 2008

Improve SOA Performance

SOA Applications Performance are disaster.

Lets assume you want to buy a book using SOA, this means you need to access several times a remote server using web service to complete the transaction, If you work with java then for each web service request you need to parse you java objects to XML objects send the request to the remote server on the other side the XML is parsed back to java objects it do it's stuff and then return a response parse it back to XML you get the XML and parse it back to java objects.

Lets assume that each of this horrible way takes 2 seconds, if you need to send 4 requests to complete the transaction it would take 8 seconds for one small transaction!!!

To improve the performance you would first need to set a well done granularity for your web services if it is possible, For example if to buy a book you first send a request to get the book name by book if and then you send a request with the book name to check if the book exists and then you send another request to buy the book, a better way would be to send one web service request which would do all of the above this would reduce the round trips between the client and the remote server, Instead of parsing XML files 2*3=6 times you would parse only 2 times.

A second way to improve the performance is to cache locally all the read only data which exists in the remote server, so instead of accessing the server using web service you would just read the data from the cache, You can also cache not read only data if you don't necessary need the last-to-update date.

Technical ways to improve the performance is to choose a good performance web service package, some packages take a lot of CPU/Memory to parse the XML to objects and vice-verse.

I recommend this SOA book to learn more:

Tuesday, January 8, 2008

Flex vs. JSF

This article would compare Flex and JSF technologies and would describe the advantages and disadvantages of each technology.

JSF Advantages:

  • Doesn't require plug in installation on the client side
  • JSF has a standard specification and it has several implementation
  • JSF has Open Source implementations which doesn't cost money.
  • Changes in the JSP files are immediately shown on the browser, no need to restart the server.

JSF Disadvantages:

  • Very complicate to develop because the basic implementation is pretty basic and for complicated UI screens need to have additional component libraries
  • Doesn't compatible between different web browsers

Flex Advantages:

  • The UI looks much nicer then JSF UI
  • Flex looks like more simple to develop rather then JSF
  • Compatible between different web browsers
  • Flex 2 SDK and Flex Builder 2 for Education are both free

Flex Disadvantages:

  • It doesn't has standard specification
  • Adobe is the only provider of Flex
  • It requires plug in installation on the client side , however this may not be disadvantage since Adobe claims that Flash is installed on more then 99% percent of users.
  • If you build a web site which users would need to search in some search engine the search engine would not be able to understand the content of the flash files (search engines can only understand standard html files/pdf files etc')
  • Flex based pages takes a lot of time to get loading compare to JSF pages
  • Flex Builder 2 costs some money

Both JSF and Flex integrate very well with java.

In summary, if you build an simple enterprise application which requires nice UI I would recommend using Flex, if you build an complicated application which requires good performance or application which is open to all the Internet users I would recommend using JSF.





Sunday, January 6, 2008

GWT Proxy

Here is a nice way to write GWT Proxy to call the server services using the proxy design pattern:

The advantages of this proxy are:

  • The client call the service as it's a local call
  • The proxy hides the difference between calling the services in hosted and development modes.
  • It improves performance since the end point is set only once

First write this Client util class:

public class ClientUtil {
private static final String PRODUCTION_URL = "http://www.koko.com";

/**
* Check if the code run in production or development mode
* @return true if we run in production mode (i.e. Ruler.html is called)
*/
public static boolean isProduction() {
return GWT.isScript();
}

/**
* Set endpoint for service which want to access the server
* @param service the service class
* @param name the name of the service
*/
public static void setEndpointForService(Object service, String name) {
ServiceDefTarget endpoint = (ServiceDefTarget) service;
String moduleRelativeURL = getRelativeURL() + name;
endpoint.setServiceEntryPoint(moduleRelativeURL);
}

public static String getRelativeURL() {
String moduleRelativeURL = null;

if (!isProduction) {
moduleRelativeURL = GWT.getModuleBaseURL();
} else {
moduleRelativeURL = PRODUCTION_URL;
}

return moduleRelativeURL;
}
}

Then write your proxy class, for example:

package com.mycompany.client.util;

import com.google.gwt.core.client.GWT;

public class MyProxy {

private static MyServiceAsync myService = (MyServiceAsync) GWT.create(MyService.class);

static {
// serviceName is the name which define in app.gwt.xml file
ClientUtil.setEndpointForService(myService, "serviceName");
}

public static void foo() {
MyCallback myCallback = new MyCallback();
myService.getServerLog(myCallback);
}
}

finally to call the server use:

MyProxy.foo();



You can read more at:

GWT Development or Production Mode

Here is a nice trick to know if your GWT application runs on hosted mode (development mode) or does it runs in production mode on a real web site.

Why do you need this? Because your access to the server side is different between development and production modes, and because you might your application behave differently between this two modes.

So to do this you would need to have two main html files one for development mode and another one for production mode, the two html are the same expect in the production mode you would put this following line:

‹iframe id="production" style="BORDER-RIGHT: 0px; BORDER-TOP: 0px; BORDER-LEFT: 0px; WIDTH: 0px; BORDER-BOTTOM: 0px; HEIGHT: 0px"›‹/iframe›

and you can also put your advertisements like Google AdSense and Google analytics and other production stuff.

after you put this write this code in your main module class:

public void onModuleLoad() {
Object isProduction = RootPanel.get("production");

if (isProduction!=null) {
ClientUtil.setProduction(true);
}

Also create this ClientUtil class:


public class ClientUtil {
private static boolean isProduction = false;

public static boolean isProduction() { return isProduction; }

public static void setProduction(boolean isProduction) {
ClientUtil.isProduction = isProduction;
}
}

Now in every place in the code user ClientUtil.isProduction() to know if you are in production or not.

Tuesday, January 1, 2008

Java becoming old?

Some "experts" claiming that Java becoming old and that it would reach it's end in a few years,
Some of these "experts" claim that java would end as Cobol, and new technologies would be adopted such as "Ruby On Rails", PHP and Ajax.

I completely disagree with this statements, First of Cobol is still one of the most common software programming languages. Beside that other new technologies such as Ruby still doesn't mature - we've tried several projects with it and have reverted to Java.
PHP is cool, but doesn't scale as well as Java for large user base applications.
AJAX -is like Javascript and CSS; It intended to be used with JSP/ASP/HTML etc.
Java still is the best choice - by far - for development. It runs on virtually any platform and doesn't lock you in to one OS vendor or flavor. It works, and it's fast. It's a great tool for back-end and web development. Yes, it's not the newest kid on the block, and frankly that doesn't matter much - It has solid performance and results pretty well in production

Links

 
RSS Feeds Submission Directory