Thursday, July 14, 2011

Reverse an Integer and String

Just tried out the very basic problem today. How to reverse an integer and string? Please let me know, if i can improve anything on this.

Integer logic 1234 = 4 *10^3+3*10^2+2*10^1+1*10^0
String logic Sarav= replace the indices value till you reach the middle.

package com.sarav.util;
/**
* @author sparamasivan
*
*/
public class ReverseUtil {

public static void main(String[] args) {
System.out.println(reverse(1234));
System.out.println(reverse("Sarav"));
}

public static int reverse(int number){
int length=String.valueOf(number).length();
int reverse=0;
while(length>0){
//int tens=(int)(Math.pow(10.00,length-1));
//reverse=reverse + ((number%10)*tens);
reverse=(reverse*10) + ((number%10));
number= number/10;
length--;
}
return reverse;
}

public static String reverse( String s ) {
int length = s.length(), last = length - 1;
char[] chars = s.toCharArray();
for ( int i = 0; i < length/2; i++ ) {
char c = chars[i];
chars[i] = chars[last - i];
chars[last - i] = c;
}
return new String(chars);
}
}


Tuesday, July 5, 2011

Protocol Buffers & Avro


I am consuming service from world's biggest market place for my site inventory. Current SLA for their services - ~200msec. I was stunned on hearing their new SLA for us ~20msec. Heard about their optimization happened on data serialization and digged little bit today to upgrade myself.

Most server-client platforms use a serialization technique to serialize into a leaner data format, and then de-serialize on the receiving end.Many languages offer native serialization APIs, but when serializing the data using the native API, Metadata about the class is serialized into the output too. is it possible to serialize only data and not with metadata?

Yes we have - Google Protocal Buffers & Apache Avro

Google Protocol Buffers
Protocol Buffers is a serialization format with an interface description language developed by Google. It is available under free software, open source license. Protocol Buffers design goals are emphasized performance and simplicity. It is a language and platform neutral technology that is an extensible mechanism for serializing structured data.

It works by you defining how you want your data to be structured via proto files, which are simply structure text files. Once you have decided the structure in your proto file, the proto executable is called on it, and a generated class (Adobe Actionscript 3, Java, C, C++, Python) is produced. The class can be generated into multiple different technologies, which means the class can be generated for the client and server technologies. Thus securing a data contract (which is type safe) between the two. The protocol buffer technology provides the ability to update the data structure without breaking deployed programs that are compiled against the old format.

Protocol buffers claims it takes between 100 to 200 nanoseconds to parse. As the overhead of the data structure is not needed in protocol buffers, only the object fields’ values is serialized. Protocol buffers will find the most compact serialization technique for a particular data type (always primitives), and only serialize fields that are not null.

Apache Avro
Avro is another very recent serialization system. It provides rich data structures that are compact, and are transported in a binary data format.

Avro relies on a schema-based system that defines a data contract to be exchanged. When Avro data is read, the schema used when writing it is always present. Similar to Protocol Buffers, it is only the values in the data structure that are serialized and sent. The strategy employed by Avro (and Protocol Buffers), means that a minimal amount of data is generated, enabling fast transport.

The schemas are equivalent to protocol buffers proto files, but they do not have to be generated. The JSON format is used to declare the data structures.

Protocol Buffers & Avro

Google’s Protocol buffer provides a much richer API for defining a data contract than Avro. Below is a list of features available to Protocol Buffers and not Avro:


  • Declare nested types

  • Define requires, repeated and optional fields

  • Specify default values on fields

  • Declare enumerations and set a fields default value from it

  • Multiple message types in the same document

  • Import other proto files

  • Declare a range of field numbers in a message available for third party extensions (Extensions) Nested Extensions

  • Define services

Avro is only compatible with C, Java and Python, but Protocol Buffers is compatible with C, C++, Adobe Actionscript 3, Java and Python.


Now you would have guessed what that company applied for their middleware solution as a push mechanism between server and client.



Sunday, June 5, 2011

How to disable the Enter key while doing form posting?



I got a problem last week in IE browser only which blocked my production roll out. As form fields, i had a quantity field with one form refresh to update the quantity and another form button to submit.

Order of my fields- Quantity , Refresh button and submit button.
We didn't specify any tab order. In all the browsers after entering the quantity,if user click enter button, it went to update the quantity. And only in this crapy IE, it went for form submit.

Here is my simple javascript which helps to solve this problem


function handleEnter(inField, e) {
var charCode;

if(e && e.which){
charCode = e.which;
}else if(window.event){
e = window.event;
charCode = e.keyCode;
}

if(charCode == 13) {
alert("We will update the quantity here what happen today: " + inField.id);
}

}

Attaching the event to field
Quantity: input type="text" id="someInput" onkeypress="handleEnter(this, event)"


Did they not code properly, while writing their user agents or did they handle unwanted usecase in which my case fell down? Why this Crap alone behaving like this?

Monday, March 30, 2009

Why Set collection has no get method?

It's a interseting question.

When we are developing a tool (kind of crawler), we had this requirement.

We used our own object and over ride the equals method. We were abou to use the get method in the set and finally realized set has no get method :)

Pasted in the sun forum for the experts view

http://forums.sun.com/thread.jspa?threadID=5375529&tstart=0

Didn't get the exact answer :(

Solution: Set internally has a Map to identify and store the unique objects. In simple whatever objects we wil place in Set, it will go as a key in the internal Map with dummy optimized value.

Carefully watching the iterator implementation of Set, it is like
return map.keySet.iterator();
Seems to be pretty simple implementation.

But get method is not such simple implementation, it needs to be iterated the whole map to identify an object.

I donno how optimized it is to traverse in HashMap, TreeMap whatever map implementation has....

But still doable, I donno Why it is missing in JDK API ?

Friday, November 30, 2007

Even eclipse has dependency graph.Why it is building all the projects?

Scenario:

Project A, B and C is dependent on say X.jar. I am updating the X.jar where those files are only related to Project A. But eclipse builds all the three projects,if the jar gets updated.

Problem: Eclipse has all the dependencies graph(I believe) and why it is behaving like this?
If its build only project A then lot of time will be saved.

Worst case scenario will be when JDK changes (I am seeing this also as a JAR changes),so only the files which are compatiable with the latest versions and it dependencies shuld be built.

It should try for the incremental build . Any thoughts guys......

Tuesday, August 7, 2007

Escape Analysis in Mustang (Java SE 6)

Escape analysis
The Java language does not offer any way to explicitly allocate an object on the stack, but this fact doesn't prevent JVMs from still using stack allocation where appropriate. JVMs can use a technique called escape analysis, by which they can tell that certain objects remain confined to a single thread for their entire lifetime, and that lifetime is bounded by the lifetime of a given stack frame. Such objects can be safely allocated on the stack instead of the heap. Even better, for small objects, the JVM can optimize away the allocation entirely and simply hoist the object's fields into registers.
Escape analysis in Mustang
This analysis is an optimization that has been talked about for a long time, and it is finally here -- the current builds of Mustang can do escape analysis and convert heap allocation to stack allocation (or no allocation) where appropriate. The use of escape analysis to eliminate some allocations results in even faster average allocation times, reduced memory footprint, and fewer cache misses. Further, optimizing away some allocations reduces pressure on the garbage collector and allows collection to run less often. Escape analysis can find opportunities for stack allocation even where it might not be practical to do so in the source code, even if the language provided the option, because whether a particular allocation gets optimized away is determined based on how the result of an object-returning method is actually used in a particular code path.
Conclusion
JVMs are surprisingly good at figuring out things that we used to assume only the developer could know. By letting the JVM choose between stack allocation and heap allocation on a case-by-case basis, we can get the performance benefits of stack allocation without making the programmer agonize over whether to allocate on the stack or on the heap.

Thursday, April 26, 2007

is all string manipulations requires synchronization?

The Java language specification assures us that strings are immutable, so most operations on a string destroy the original object and create a new one. But in reality the compiler can optimize the operation and reuse the same memory as the original string. For instance we have a string ‘String stringSample = "Saravanan";’ stored in memory at memory location m1. The compiler will store this String in memory as origin location = m1 and offset = 12.

Now when an operation ‘stringSample = stringSample.substring(4);’ is done, stringSample will contain "vanan".

As per the Java specification we would assume that stringSample will be moved to a new location m2 and the old memory location is left for the garbage collector, but compilers can reuse the same memory location and update the offsets. So the new string after the sub string operation would read as origin location = m1+4 and offset = 8. This does not break the Java specification, as the old reference is lost and a new reference is created with a new origin location and a new offset. The problem is when two threads try to access this string at the same time; the second thread might get the wrong starting location.