Thursday, January 13, 2011

synchronized vs custom locking: Java synchronization performance

If you have paid close attention to locking and synchronization mechanisms in Java, you must have noticed that there were better locks introduced in Java 1.5. It was basically Doug Lea's concurrent programming library that was standardized as JSR 166. The most notable introduction of the ReentrantLock. This gives developers a finer control over locking than synchronized keyword. synchronized by default is an exclusive lock and for classic cases such as Reader-Writer problem, it performs very poorly. The Java code segment at the end of this note tests the performance difference between the two locking mechanisms. Below are the results of this test

NO_LOCK operations/second 403,348,600

RE_ENTRANT_LOCK operations/second 24,345,620
SYNCHRONIZED operations/second 5,340,017
NO_LOCK operations/second 518,446,185
RE_ENTRANT_LOCK operations/second 23,242,504
SYNCHRONIZED operations/second 5,270,688
NO_LOCK operations/second 541,463,736
RE_ENTRANT_LOCK operations/second 23,193,530
SYNCHRONIZED operations/second 5,448,608

A quick glance at the results will tell you that ReentrantLock is at least 5 times faster than the exclusive synchronization. You might also conclude that you should ditch synchronized altogether. But it must be understood that taking control of locking, you ought to be very careful with the way you use it. The first thing to remember is to use try...finally block even if you don't intend to capture any exception. Also, it is a good idea to refresh your ideas about Mutexes, Semaphores and Thread Monitors. Another advantage of using custom locks is when you need finer control over the order in which locks can be acquired and released.

Above tests were performed with Oracle Java SDK 1.6.0_2. However, according to this article on Sun employee's blog both synchronized keyword and custom locking should be equally performant with the modern JVMs. The article gives insight on implementation details of synchronization in Java

LockPerformanceCheck.java

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockPerformanceCheck implements Runnable {
enum Mode implements Runnable {
NO_LOCK {
public void run() {
operation();
}
},

RE_ENTRANT_LOCK {
private final Lock lock = new ReentrantLock();

public void run() {
lock.lock();
try {
operation();
} finally {
lock.unlock();
}
}
},

SYNCHRONIZED {
public synchronized void run() {
operation();
}
}
}

private final Mode mode;
private final int count;

public LockPerformanceCheck(Mode mode, int count) {
this.mode = mode;
this.count = count;
}

public void run() {
for (int i = 0; i < count; i++)
mode.run();
}

public static void operation() {
int a = 2 * 2;
}

private static void test(Mode mode) throws InterruptedException {
int threadNumber = 4;
int count = 1000 * 1000;
long start = System.nanoTime();
Thread[] threads = new Thread[threadNumber];
for (int i = 0; i < threadNumber; i++)
(threads[i] = new Thread(new LockPerformanceCheck(mode, count)))
.start();
for (int i = 0; i < threadNumber; i++)
threads[i].join();
long rate = 1000L * 1000 * 1000 * count * threadNumber
/ (System.nanoTime() - start);
System.out.printf("%s operations/second %,d%n", mode.toString(), rate);
}

public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 3; i++) {
test(Mode.NO_LOCK);
test(Mode.RE_ENTRANT_LOCK);
test(Mode.SYNCHRONIZED);
}
}
}
Sphere: Related Content

Tuesday, November 9, 2010

Why is Pune so expensive?

This morning I was trying to book movie tickets through BookMyShow. It turns out Mumbai and Pune have the most expensive movie tickets. The rate may be justified by at least by the ambience of BIG Cinemas Metro. But I fail to understand why GOLD at Kalyani Nagar should be so expensive.

So, I did a quick comparison of most expensive ticket at BIG cinemas in each city for Golmal 3. The findings are shocking. The median ticket rate is 180 INR while Mumbai and Pune are asking for almost double the same.


Show: Golmal 3 9th November 2010



Mumbai (South) BIG Cinemas: Metro 350
Mulund BIG Cinemas: Mulund 180
Pune BIG Cinemas: GOLD 350
Chinchwad BIG Cinemas: Chinchwad 175
Bangalore BIG Cinemas: Arch Mall 200
Hyderabad BIG Cinemas: Gold Spot 150
Nashik BIG Cinemas: Divya 100
Vashi BIG Cinemas: Palm Beach 220
Aurangabad Anjali BIG Cinemas 60

Is it just me who is feeling the pinch? Can anyone explain economics behind such exorbitant pricing?
Sphere: Related Content

Wednesday, June 10, 2009

Are WWW browsers really secure?

You are writing a Web 2.0 widget. You want it to be hosted on your site but embedded in third-party sites. You also want it to exchange data with your site. You would naturally consider XmlHttpRequest. Since you use have been using it extensively to write all your AJAX code. But that is not going to work from the third party site where your widget will be embedded. Any attempt to load data from your site is going to be a security issue. It's formally known as XSS (Cross-Site scripting). And is quite rightly blocked by the browsers.

A wise developer would say, "let's use an iFrame and point it to any URL we want. Then we can get its contents by accessing innerHTML or innerText from DOM". This then would be kicking a** of the smartest programmers hired by the "smartest" companies of the first world. Unfortunately, however this is a kind of statement only a tyro can make.

Having said that, luckily, the developers of (allegedly) bullet-proof browsers are not that smart. As Web in it's early days looked forward to a rosy future (though beset on all sides by a desultory present). Visionaries convinced commons that everybody was going to use a web browser. Everything was going to happen in the browser. They also told people that browser would render a new markup code HTML. Then they wrote the specifications. Which were shambolic. And if they were any good, neither did anybody have time to respect the specs nor did anyone care! Amidst this progress, a new language tailored for the web, christened "Javascript", was born. Zealots then also promised that e-commerce was the way to go. They pushed the browser makers to come up with ways to support it. And this another instance of chaos theory ended in an unholy mating of Javascript and the WWW Browser.

As I said due to web's haphazard growth there are numerous loopholes in the entire ecosystem. I recently came across a hack to get out of the boundaries circumscribed by a browser: Loading Javascript from a third-party site. Now, it is really surprising why this is not considered a security issue because allowing Javascripts to load from third-party sites totally defeats the purpose of having XSS security in place. You can do pretty much everything with it that you would otherwise do with standard AJAX. I learned in detail about XSS when my progress was impeded while writing a Web2.0 gadget/widget that required cross-site data exchange. I was able to work out a solution within a few minutes. It is fairly straightforward. Whenever you want to load data from remote site, all you have to do is create a new Javascript element and append it to DOM. Now on the server side make your dynamic scripting enging spit out a Javascript that calls another already defined function. This newly received function however contains the data that you were set out to ferry. I'm sure this is a commonly known/used solution. That leaves me with a final question, why is this still possible if an average Joe like me could figure it out in minutes? Pondering over the question for a while I got the answer myself. The answer is "Google" or any I advertising company/aggregator for that matter. Finally it boils down to another unanswerable question, "Otherwise, how would they push adverts on third-party sites? or How would Google Analytics collect data about your users (oops!)"
Sphere: Related Content

VVT explained

Here http://auto.belsare.in/2009/06/time-it-well.html
Sphere: Related Content

Wednesday, May 20, 2009

Finally I got a PVR/DVR solution

Good features are:
  • stores 48 hrs of video
  • recording quality is superb. can record from analog source also
  • built-in STB
  • unlike Tata Sky+ you can forward recorded videos
  • you get USB and Ethernet connectivity to copy recorded videos and control device remotely
  • no subscription charges like TiVo for EPG based recording & scheduling
It's pricey though. At Rs. 10k , it isn't a great buy given the quality of programming on cable.



Connections


List of Recorded items



Sphere: Related Content

Wednesday, September 3, 2008

Google Chrome – A desperate attempt to get back at Microsoft

Google has made it a habit to make hype of their products before launch. Yesterday’s accidental launch of their new browser Chrome was just another instance. Having said that, the first thing that I did this morning was downloaded it myself.

So, here is my take on Chrome:
To begin with, the download available on Google site was a stub and not the complete browser. The rest of the package was downloaded after running the stub. The installation was started once missing bits were downloaded. The installation was pretty simple and went without any issues for me. But when installation was done, Chrome started importing my Firefox profile without my permission. There was no way to cancel the “import” operation either. Finally, the browser greeted me with a blank page with no toolbars or menubars except an address bar which is also an overloaded search bar. Tab bar takes place of the window title bar. Overall, the appearance closely resembles that of Apple Safari, which in reality is a foundation for the browser.

Before we go into the detailed feature list, let’s quickly look into the (stolen) building blocks of Chrome. The core of the browser, its rendering engine is Webkit. Yeah, the same one that is used by the Apple Safari. Look and feel is stolen from… again Safari. Even the in-page text search is ditto Safari. The startup page resembles Opera’s speed dial. It shows screenshots of your most recently visited pages along with the bookmarks (in my case imported from Firefox) in the right pane. There is no bookmark menu or sidebar. By default, the bookmark bar is hidden and available using keyboard shortcut Ctrl + B. ‘InPrivate’ mode from IE becomes “incognito” window in Chrome.

And the (missing) feature list is here:
1. No add-ons/plug-ins: Firefox users have been spoilt by the extensive add-ons that virtually make Firefox a full-blown platform in itself.
2. No shortcut to clear private data
3. No Firebug, delicious, StumbleUpon
4. And what about the Themes?

The only plus you notice about Chrome is that it fast, ultra fast. But that too comes at a cost. How did they achieve a good rendering speed? A, they could have used something like “Google Accelerator” to tunnel everything through their servers and caches to improve network speed. But, it doesn’t sound like a viable option. B. Strip-down/off less prominent features. For example, rendering quality

An interesting comparison of the same rendering engine in two different browsers shows that the CSS/Image rendering quality in Chrome is extremely poor.
http://www.flickr.com/photos/kurafire/2822606444/


All in all, Google Chrome is ages behind the frontline browsers. Howbeit, I’m sure Chrome will be a super hit browser. It’ll also eat into IE’s market share. It will all not happen because it is a good browser, but because it is from Google. One thing I hate about Google is that, they think anything and everything they do is “cool” and it is “the way it should be”. That is usually not the case. I’m definitely not an anti-Google person. In fact, most of the services I use on the Internet are from Google. But it’s probably the high time when they should know that they can’t do everything.
Sphere: Related Content

Monday, May 12, 2008

A random pause from blogging

As you must have noticed, I took a random two week break from blogging. I have been trying to become a regular blogger for a while now. This is my third serious attempt at writing blogs. But for some reason or the other, I fail to maintain regularity. Not that I'm regular in everyday things. Ask my Mom. She would tell you how lazy person I am.

But here is a promise that new random musings will make appearances on the blog once or twice a week.
Sphere: Related Content