Lock – Java

Hello world, today I gonna talk about Lock. Yes it’s lock from java se7 if not mistaken.  It come in handly while serveral threads need to access a common data / class during running time.

 

It really draw my attention as a newbie of Java language. Still remember back to the day when I was first year student in Uni, one of the assignment require to implement mutax in multi thread environment (C++). It bother me a lot ;(  Couldn’t imagine how handy is it when come into Java. All about trylock( ) and unlock( ).

By explaining the usage of Lock under Java environemtn, I decide to code a exmaple for demonstraction. Link can be found in following:
https://github.com/andykhk/All-About-Java/blob/master/String_Joiner/src/Lock/Customer.java

Ok, just imagine you are a uni student. your lappy die straight during the middle of the day. As you are a normal 90’s kid , how can we tolerance a day without internet? So you rush to downtown and gonna a new laptop straight away.

By the time you step into the store, two salesman about to approache you, they are selling Mac and Acer laptop respectively. Ya, you proabably won’t face this kind of situation in real life, as they belong to the same store. But anyway dun jundge, it’s “Story”.

Just pretent you don’t have any preference of brand, would simply go with last brand promoted by salesman. Here is the rule:
– Every sales have 3 seconds to sell his product
– Sales can only apporache to sell you while you are free (Which is not occupted by other sales).

On order the clarify the situation, I put all in single memo pad if it’s make sense.
20160922_231017

As shown, you gonna stay in the store for five seconds, the Mac sales appproach you at first sight. As your locked is not invoked by any sales, he have you for 3 seconds (Obtained the Lock)….

locked = customer.lock.tryLock();
It would return true as no one invoke the lock yet.

All things go well until 2seoncds after Acer sales come by and try to sales you a Acer lappy. However when he try to obtain the Lock by:

booleanlocked = false;
locked = customer.lock.tryLock();

However as customer is busy, it return false. So Acer salesman just leave in a sad shape. And you end up getting a Mac.

Yup, here it is. Simple example to show how lock work when adopting the real world case, it just come into my mind when I learning the concept of Lock in java. That’s why I did wrote it down for Blog and here we go;)

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s