<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ashwani tiwari on Medium]]></title>
        <description><![CDATA[Stories by Ashwani tiwari on Medium]]></description>
        <link>https://medium.com/@ashwani-the-tiwari?source=rss-d2dfb368cb55------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*2tA6pNumg1FLYjUC.jpg</url>
            <title>Stories by Ashwani tiwari on Medium</title>
            <link>https://medium.com/@ashwani-the-tiwari?source=rss-d2dfb368cb55------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:29:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ashwani-the-tiwari/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Blockchain Concepts Through Bitcoin/Ethereum/EOS -2.]]></title>
            <link>https://ashwani-the-tiwari.medium.com/blockchain-concepts-through-bitcoin-ethereum-eos-2-c6728ddcc546?source=rss-d2dfb368cb55------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6728ddcc546</guid>
            <category><![CDATA[bitcoin-transfer]]></category>
            <category><![CDATA[bitcoin-wallet]]></category>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Ashwani tiwari]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 15:24:56 GMT</pubDate>
            <atom:updated>2020-11-26T15:26:00.049Z</atom:updated>
            <content:encoded><![CDATA[<h3>(Sending and Receiving Bitcoin)</h3><p>Second blog of these series. Here I m explain how the sending and receiving in bitcoin happens.</p><p>As we know bitcoin is the protocol that can access using a client application that know the protocol. Just like http is protocol , web browser is the client to interact with http. A “Bitcoin Wallet” is the most common user interface to connect with bitcoin system. There are many implementation and brands of bitcoin wallet , just like the web browsers ( chrome , safari , Internet explorer). Bitcoin wallet vary in quality , performance , security and reliability. There is also a reference implementation of the bitcoin protocol that includes a wallet , known as the “Satoshi Client” or “Bitcoin Core” which derived from the original implementation written by Staoshi Nakamoto.</p><p>Aswani just heard about bitcoin and want to use it. For this he download a “Mycelium” . When he run “Mycelium” , it create a new wallet for the him.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*QKlEpRBpsrE1dOYD5WLOQg.png" /></figure><p>The above screen shot show the bitcoin address appears as string and number. A bitcoin address is start with 1 or 3 like. Like a email address, they can be shared with other bitcoin user who can use them to send bitcoin directly to your wallet. There is nothing sensitive , from security perspective , about bitcoin address. It can be posted anywhere without risking the security of your account. Unlike email address, you can create new address as often you like, all of which will direct funds to your wallet. In fact many wallet lets automatically create a new address for every transaction to maximize privacy. A wallet is simply the collection of address and keys that unlock the funds within.</p><p>Wallet application randomly generate a private key (more details on later blogs) together with its corresponding bitcoin address.</p><p>At this point aswani bitcoin address is simply a number corresponds to a key that he can use to control access to fund. This address is generate independently by his wallet without reference to or register with any service. Only once it has been associated with a transaction does it become part of the known address in the network.</p><p>Bitcoin transaction are irreversible. But the electronic payment is reversible. You simply can buy the bitcoin. You have to find your any friends or service from where you can purchase the bitcoin in exchange of anything or paper currency.</p><p>Aswani get his first bitcoin from his friend Sunny . Next we will look at how he buy bitcoin from his friend sunny and how sunny sends the bitcoin to his wallet.</p><p><strong><em>Who sets the bitcoin price?</em></strong><em><br>The short answer is that the price is set by markets.<br>Bitcoin, like most other currencies, has a floating exchange rate. That means that the value of bitcoin vis-a-vis any other currency fluctuates according to supply and demand in the various markets where it is traded. For example, the “price” of bitcoin in US dollars is calculated in each market based on the most recent trade of bitcoin and US dollars. As such, the price tends to fluctuate minutely several times per second. A pricing service will aggregate the prices from several markets and calculate a volume-weighted average representing the broad market exchange rate of a currency pair (e.g., BTC/USD). There are hundreds of applications and websites that can provide the current market rate.</em></p><p>Aswani decide to exchange 10 dollar for bitcoin. So he gives 10 dollars to sunny and then open his wallet and press the receive button. As press the receive button a QR code is displayed as bitcoin address. Now sunny just click on send button on his wallet . He have to provide to information to send the money a destination address and amount he want to transfer.</p><p>Sunny just scan the QR code of Aswani .Put the amount (10 dollars ) , wallet will automatically convert the US dollars to bitcoin by accessing the most recent exchange rate an online service. Suppose exchange at that time is 100 dollars per bit coin. So his wallet convert 10 dollars to bitcoin which 0.10(BTC) bitcoin or 100 milibitcoin (mBTC).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*nsON4S0ATyI7LCqBM3Q11w.png" /></figure><p>Now after entering the amount , Sunny check carefully that he entered the correct amount because bitcoin transaction is irreversible. As he press “send button” , his wallet construct a transaction that assign 0.10 BTC to the address provide by Aswani , sourcing the funds from Sunny wallet and signing the transaction with Sunny private key. This information tells the bitcoin network that Sunny authorized a transfer of value to Aswani new address. Now the transaction in transmitted on peer-to-peer network , and propagates across the bitcoin network. Within a second most the nodes connected to bitcoin network receive the transaction and see the Aswani address first time.</p><p>Meanwhile “Aswani” wallet is constantly “listening” all the published transaction in the bitcoin network, matching the address. Once the address is matched , he will receive the bitcoin. It will take a few sec.</p><p><strong><em>How the confirmation work ?</em></strong><em><br>Bitcoin is received in Aswani wallet but its status is showing “Unconfirmed”. The goes in “Confirmed” state when the transaction is added to the block , and block is included in the transaction ledger , know as blockchain. “Unconfirmed” state show that the transaction has been propagated to the network but not yet been included in blockchain. Block is entered in blockchain in every 10 minute. Changing of transaction from “Unconfirmed” state to “Confirmed” state , in traditional financial term , known as “clearing”.(We will discuss more in details later about propagation, validation, clearing (confirmation) of bitcoin transaction).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6728ddcc546" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blockchain Concepts Through Bitcoin -1 (Introduction)]]></title>
            <link>https://ashwani-the-tiwari.medium.com/blockchain-concepts-through-bitcoin-1-introduction-9518b9582319?source=rss-d2dfb368cb55------2</link>
            <guid isPermaLink="false">https://medium.com/p/9518b9582319</guid>
            <category><![CDATA[bitcoin]]></category>
            <category><![CDATA[blockchain]]></category>
            <dc:creator><![CDATA[Ashwani tiwari]]></dc:creator>
            <pubDate>Wed, 25 Nov 2020 08:22:15 GMT</pubDate>
            <atom:updated>2020-11-26T15:39:06.145Z</atom:updated>
            <content:encoded><![CDATA[<h3>Blockchain Concepts Through Bitcoin/Ethereum/EOS -1 (Introduction)</h3><p>This is series of blog where I am going to explain the every single concepts of blockchain in depth using the bitcoin as reference implementation and also other concepts used in open source blockchain provider EOS and Ethereum(for smart contract and Dapps). These blog are mainly for the developer who wants to learn and understand the blockchain.</p><p>The blog first cover the bitcoin implementation and use of their technology after that I will cover Ethereum and EOS. Why first bitcoin ? because bitcoin is the foundation of blockchain , to get the deep understanding we have to first start form the start. Then will learn what are the challenges of bitcoin and how Ethereum and EOS solved it and provide extra and generic feature so that we can use blockchain in other application rather than only in cryptocurrency .</p><p>This is first blog of these series which mainly introduce the Bitcoin/Blockchain terms and basic concepts.</p><p><strong>What is bitcoin ?</strong></p><p>If you new to bitcoin , you think bitcoin is the digital currency. But it is more than that , it is first kind of innovation which introduce new technology to the world. We can say it is collection of concepts and technologies that form a new digital money ecosystem.</p><p>Unit of currency called bitcoin which is used to store and transmit value among participants in the bitcoin network. A bitcoin user communicate with each other using the bitcoin protocol (open source — run on every device).</p><p>User can transfer the bitcoin over the network to do just anything that can be done with conventional currency (buy , sell good , send money etc.)</p><p>The bitcoin is implied in transaction that transfer value from sender to recipient. Users of bitcoin own keys that allow them to prove the ownership of bitcoin in bitcoin network. With these key they can sign transaction to unlock the value and spend it by transferring it to new owner. Key are often store in a digital wallet on each user computer or smartphone. Possession of the key that can sign the transaction is only the prerequisite to sending bitcoin, putting control is the hands of each others.</p><p>Bitcoin is a distributed , peer to peer system. (No central server, or single point of control).</p><p>Bitcoin is created through the process called “mining” (which involves competing to find solution to a mathematical problem while processing the bitcoin transaction). Any participating in the bitcoin network (any one who is running the whole bitcoin protocol stack) may operate as a miner using their computation processing power to verify and record the transaction.</p><p>Every 10 minutes , on avg., a bitcoin miner is able validate the transaction of the past 10 minutes and is reward with new bitcoin. Bitcoin mining decentralize the currency -issuance and clearing the function of a central bank and replace the need of central bank.</p><p>Bitcoin protocol includes built-in algorithm which adjust the mining function across the network. The difficulty of processing task that miner must perform adjusted dynamically so that , on average , someone succeeds in every 10 min .</p><p>The protocol also halves the rate at which new bitcoin is created every 4 year , limit the total no of bitcoin that will be created to be fixed total just below 21 million coins. Due to Bitcoin diminishing rate of issuance , over long period of time , bitcoin is deflationary.</p><p>Behind the scene , bitcoin is also the name of the protocol , peer-to-peer network and distributed computing innovation.</p><blockquote><em>Bitcoin represents the decades of research in cryptographic and distributed system and includes four key innovations brought together in unique and powerful combination. Bitcoin consists of <br>1 . </em>A decentralized peer-to-peer network (the bitcoin protocol).<br>2. A public transaction ledger (blockchain).<br>3. A set of rules for independent transaction validation and currency issuance (Consensus Rule).<br>4. A mechanism for reaching global decentralized consensus on the valid block chain (Proof of work algorithm).</blockquote><p>To read second of this blog series <a href="https://ashwani-the-tiwari.medium.com/blockchain-concepts-through-bitcoin-ethereum-eos-2-c6728ddcc546">https://ashwani-the-tiwari.medium.com/blockchain-concepts-through-bitcoin-ethereum-eos-2-c6728ddcc546</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9518b9582319" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Lock Framework- Lock Interruptible Feature-Part 2]]></title>
            <link>https://ashwani-the-tiwari.medium.com/locking-framework-lock-interruptible-feature-part-2-b831ff2eecc1?source=rss-d2dfb368cb55------2</link>
            <guid isPermaLink="false">https://medium.com/p/b831ff2eecc1</guid>
            <category><![CDATA[lock-vs-lockinterruptibly]]></category>
            <category><![CDATA[java-concurrency]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[lock-framework]]></category>
            <category><![CDATA[java-lock]]></category>
            <dc:creator><![CDATA[Ashwani tiwari]]></dc:creator>
            <pubDate>Sat, 24 Aug 2019 18:26:29 GMT</pubDate>
            <atom:updated>2019-08-25T19:01:09.979Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Lock Framework- Lock Interruptible-Part 2</h3><p>Here we learn the feature provided by the Lock with its methods. We also compare what we cannot do with synchronize.</p><h3><strong>Lock Interruptible</strong></h3><p>Lock Interruptible means you can be interrupted a thread while the thread in waiting state /blocking state.</p><p>Try to acquire the lock is the blocking operation and if the blocking operation not throwing InterruptedException it cannot be interrupted . Both <em>synchronize</em> and void <em>lock()</em> not declare to throw any exception. So it cannot be interrupted while waiting for the lock.</p><p>In case of Lock if some thread is waiting/block for the lock , it can interrupted while waiting/block state by another thread.</p><p>In case of synchronize a Thread-A can not interrupt the Thread-B if Thread -B is in waiting state.But in Lock interface you can interrupt a waiting thread/block thread.</p><blockquote>So in the short way we can say following two point.<br>1. <strong>Synchronize</strong> provide the non-interruptible blocking mechanism <br>2. <strong>Lock</strong> provide provide interruptible blocking mechanism .</blockquote><p>This interruptible blocking feature is provide in Lock by <strong><em>void lockInterruptibly()</em></strong><em> method.</em></p><p><em>Lets look into the code</em></p><pre>private final Lock lock = new ReentrantLock();<br>   public void m() throws InterruptedException {<br>     lock.lockInterruptibly();  <br>     try {<br>       // ... method body<br>     } finally {<br>       lock.unlock()<br>     }<br>   }</pre><p>In the above we use <strong><em>void lockInterruptibly() </em></strong>try to acquire a lock and if lock is not available the thread is blocked but<strong><em> </em></strong>when the thread.interrupt method was called by another thread it throws an <strong>InterruptedException </strong>and get<strong> </strong>out from blocked state. This allows to interrupt the processing even while trying to acquire a lock.Which is not possible with synchronize.</p><p>Let try to understand using a example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f921e24f719a12ddad8676f7ce60df7a/href">https://medium.com/media/f921e24f719a12ddad8676f7ce60df7a/href</a></iframe><pre>OUTPUT -<br>Before entering to acquire the lock<br>Interrupted</pre><p>In the above , the thread first thread acquired the lock on the lock object then start the second thread , after that the first thread call interrupt method on the second thread. Since the lock is already acquired by the calling (first thread ) thread , when the second thread goes to acquire a lock it will block and then throw the InterruptedException while int waiting/block state because we call interrupt() method .</p><p>So use when is it important to force a thread to interrupt while it is acquiring a lock.</p><p><strong>Interruptible Mode Vs Non-Interruptible Mode.</strong></p><p>The Lock framework provide two mode to get the lock one interruptible and anthoer is non-interruptible. The Interruptible mode feature is provided by void lockInterruptibly() method and non-interruptible mode feature provide by void lock() method.</p><p>Let look into both mode</p><p><strong>Non-Interruptible Mode-void lockInterruptibly()</strong></p><p>When we call void lock(), we try to acquire lock in a non-interruptible mode which means even if the thread waiting in queue is interrupted or unparked ( thread unpark means permit is available to try for a lock), it is going to simply retry to acquiring the lock. This goes on, resulting in blocking and unblocking of the thread till it acquires the lock.</p><p><strong>Interruptible Mode -void lock()</strong></p><p>We can try acquiring lock in exclusive interruptible mode using void lockInterruptibly() in which case if the thread in waiting is interrupted by some other thread it will result in InterruptedException thus there won’t be any retry. If the thread is unparked as a result of release of lock then it is going to retry acquiring lock.</p><blockquote>The un-interruptable lock will block when lock.lock() gets called until the thread that currently owns the lock releases it. If the thread that currently owns the lock never releases it then this thread can’t get the lock and will be blocked forever. This is analogous to the normal operation of the synchronized (object) { } block. The method will block while trying to get a lock on the object, when it does it proceeds.</blockquote><p>The exception throw not declare dose not mean that it cannot be interrupted , it can interrupted between lock() and unlock() but not at time of trying to acquiring the lock. You can use boolean isInterrupted() method as usual in case of the lock and unlock to check thread interrupted or not.</p><pre>class Chill implements Runnable<br>{<br>    @Override<br>    public void run()<br>    {<br>        Lock.lock();<br>        try<br>        {<br>            bar();<br>            if (Thread.isInterrupted()) return; // finally block will be called<br>            bar();<br>            if (Thread.isInterrupted()) return;<br>            bar();<br>        }<br>        finally<br>        {<br>            Lock.unlock();<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b831ff2eecc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Lock Framework — what synchronization and wait/notify not offer- Part 1.]]></title>
            <link>https://ashwani-the-tiwari.medium.com/locking-framework-what-synchronization-and-wait-notify-not-offer-part-1-f11af6b633f0?source=rss-d2dfb368cb55------2</link>
            <guid isPermaLink="false">https://medium.com/p/f11af6b633f0</guid>
            <category><![CDATA[reentrant-lock]]></category>
            <category><![CDATA[lock-vs-synchronize]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[java-locking-framework]]></category>
            <dc:creator><![CDATA[Ashwani tiwari]]></dc:creator>
            <pubDate>Sat, 24 Aug 2019 10:53:24 GMT</pubDate>
            <atom:updated>2019-08-25T18:31:22.894Z</atom:updated>
            <content:encoded><![CDATA[<h3>Java Lock Framework — what synchronization and wait/notify not offer- Part 1.</h3><p>Part 1- Introduction — with difference between lock and synchronize<br>Part 2- Lock framework-Feature in depth with example.<br>Part 3- Look into various classes their feature and example.<br>Part 4- Locking framework in depth -how implemented own custom lock .<br>Part 5- Collection of some important question and problem.</p><p>The<em> java.util.concurrent</em>.<em>locks</em> package provide a new way of locking and waiting condition which is different from object’s intrinsic lock based synchronization and <em>java.lang.Object</em> wait/notification mechanism.</p><p>Why create a new locking mechanism that is so similar to intrinsic locking? Intrinsic locking works fine in most situations but has some functional limitation like not possible to interrupt a thread waiting to acquire a lock, or to attempt to acquire a lock without being willing to wait for it forever. Intrinsic locks also must be released in the same block of code in which they are acquired; this simplifies coding and interacts nicely with exception handling, but makes non-blockstructured locking disciplines impossible. None of these are reasons to abandon synchronized, but in some cases a more flexible locking mechanism offers better liveness or performance.</p><p>ReentrantLock implements Lock, providing the same mutual exclusion and memory-visibility guarantees as synchronized. Acquiring a ReentrantLock has the same memory semantics as entering a synchronized block, and releasing a ReentrantLock has the same memory semantics as exiting a synchronized block. ReentrantLock supports all of the lock-acquisition modes defined by Lock, providing more flexibility for dealing with lock unavailability than does synchronized.</p><p>It make easy to learn the Locking framework with comparing in synchronize. Its become easy to understand the concept of new lock and why we need the lock framework?.</p><blockquote><strong>What synchronization offers.<br></strong> Synchronization provide a safe way for threads to updated the shared variable and ensure that a thread updates are visible to each other. You use <strong><em>synchronize</em></strong> keyword on method or to on a code block which is known as <strong>critical section</strong>.</blockquote><blockquote>So Synchronization offers.<br> 1. Safe update of shared variable.<br>2. Updates must visible to each thread.</blockquote><blockquote><strong>How synchronization work. — if you are here you know very well.</strong></blockquote><p><strong>Classes and Interface in lock framework which we cover.</strong><br> <em>1.</em><strong><em> Lock Interface</em></strong><em><br> 2. </em><strong><em>ReenterantLock</em></strong><em> Class — implements Lock Interface<br> 3. </em><strong><em>ReadWriteLock</em></strong><em> Interface<br> 4. </em><strong><em>ReenterantReadWriteLock</em></strong><em> Class — implemets ReadWriteLock Interface<br> 5. </em><strong><em>ReenterantReadWriteLock.ReadLock</em></strong><em> class — it is the static class inside ReenterantReadWriteLock and it implements Lock interface<br> 6. </em><strong><em>ReenterantReadWriteLock.WriteLock</em></strong><em>- it is the static class inside ReenterantReadWriteLock and it implements Lock interface.<br>7.</em><strong><em> StamptedLock.</em></strong></p><h4><strong>Lock Interface</strong></h4><p>It provide locking operation which is also provide by lock associated with monitors (means by synchronization) and it offers more operation like you can immediately back out of a lock-acquisition attempt when lock isn’t available.</p><p><strong>Methods in interface.</strong></p><p><strong>void lock()</strong>: Acquired the lock. When the lock is not available , the calling thread wait until its available. (synchronize also offer this by keyword).</p><p><strong>void lockInterruptibly()</strong>: Acquired the lock unless the calling thread is interrupted. When lock is not available the calling thread wait for the lock. While wating for the lock if thread is interrupted it throws java.lang.InterruptedException and exits the method call.</p><p><strong>Condtion newCondition()</strong>: This method return the new Condition instance.<br>The Condition instance is bound to the Lock from which you get.<br>If the Lock implementation class not support the conditions then this method throw java.lang.UnsupportedOperationException.</p><p><strong>boolean tryLock()</strong>: When you call this method to acquire the lock and if lock is available at time of calling the method then it acquire. This method return true when lock is acquired and false when the lock isn’t required. This method is not blocking</p><p><strong>boolean tryLock(long time, TimeUnit unit)</strong>: Its acquire the lock when its available within the specified time and the calling thread is not interrupted.<br>If lock is not available its wait for lock within waiting time. When the lock is acquired return true , if not return false.</p><p><strong>void unlock()</strong>: Release the lock.</p><p><strong>Note :- We learn more in depth in next part about the these above method.</strong></p><p><strong>Syntax<br></strong>Before we dive into depth its is very helpful if we know the basic syntax to acquire and release a lock. You already know about the syntax of synchronized keyword.</p><p>Idiom for lock acquisition and release</p><pre>Lock l= ………..; //….some class object who implements Lock interface<br>l.lock();<br>try<br>{<br>//access the critical section</pre><pre>}catch(Exception ex){<br>}<br>finally<br>{<br>l.unlock();</pre><pre>}</pre><p>This idiomis somewhat more complicated than using intrinsic locks: the lock must be released in a finally block. Otherwise, the lock would never be released if the guarded code were to throw an exception. When using locking, you must also consider what happens if an exception is thrown out of the try block; if it is possible for the object to be left in an inconsistent state, additional TRy-catch or TRy-finally blocks may be needed. (You should always consider the effect of exceptions when using any form of locking, including intrinsic locking.)</p><p><strong>What we know about ?<br>1. Synchronized Context <br>A. All lock acquisition and release occurs in code blocked structure.<br>B. When multiple lock is acquired they released in opposite order.<br>C. All lock released in same lexical scope in which they were acquired.<br>D. All the acquisition of lock is block the calling thread if lock not available.<br>E. Multiple condition on same lock not possible.</strong></p><p><strong>2. Lock Context — ( read the methods of lock carefully)</strong><br><strong>A. All lock acquisition and release doesn&#39;t need the code block structure.<br>B. We can release the lock in any order<br>C. No need the same lexical scope to release a lock in which they were acquired<br>D.Lock Interface provide some method which non-blocking method.<br>E. Multiple condition on same lock is possible.</strong></p><p><strong>Point A.</strong><br><strong>Synchronization — All lock acquisition and release occurs in blocked structure.<br>Lock Interface -All lock acquisition and release doesn’t need the block structure.</strong></p><p><strong>What is code block ?</strong><br> A code block means a grouping of two or more statements.In Java you create a code by putting the opening and closing braces around the statement<br>like below is the code block.</p><p>if(a &lt; b){ // opening bracket<br>a=a+b;<br>b=0;<br>}//closing bracket</p><p>A method is also a code block because in method all the statement written in between two bracket.<br>So when you use the synchronized keyword on the method (code block), then lock is acquired by the thread when it call the method and released the lock when it leave the method.So the lock associated with synchronized keyword depends on the method start (opening bracket of code block )and the method end (closing bracket of code block).<br>public synchronized void someName(){//lock acquired<br> //Critical Section<br>}//lock released</p><p>And there is also a another way to use the synchronized keyword to acquired and release lock ,if you dont want to synchronize whole method, a synchronize block.<br>synchronized(someObjectReferance){<br>//critical section</p><p>}<br>synchronized block work as same as you use synchronize the method , the thread acquire the lock when hit the opening braces and release the lock when hit the closing bracket.</p><p>I think you got it what i want to explain. The synchronize keyword depends on the code block to get the lock and to release the lock</p><p>Let see how Lock interface not depend on code block.<br>Since the Lock interface provide a method to get the lock (void lock()) and to release the lock (void unlock()).<br>So it up to you where u call the void lock() method to get the lock and void unlock() method to release the lock not on where the code block start and where it ends.</p><p><strong>Points B.</strong><br><strong>Synchronization — When multiple lock is acquired they released in opposite order<br>Lock Interface — We can release the lock in any order.<br></strong>In the case of synchronized , the release of lock is follow LIFO order.<br>Lets understand the LIFO of synchronized with example nested synchronized block<br>synchronize(objectA){ // get lock on object A</p><p>synchronize(objectB){ // get lock on object B</p><p>}//released lock object B</p><p>}//released lock of object A</p><p>From the above example , you find that the release of lock is in opposite of the acquisition of lock.<br>But in the case of Lock interface we can release the lock in any order.</p><p><strong>Point C.</strong></p><p>In case of lock we can do like this</p><pre>public class Test {<br>    Lock l = new ReentrantLock();<br><br>    void myMethod1() {<br>        l.lock();<br>        // Do my stuff here<br>    }<br><br>    void myMethod2() {<br>        // Do more stuff here<br>        l.unlock();<br>    }<br>}</pre><p>You can acquire the lock in one method and release in another , which is not possible in case of synchronize.Since both method in different scope you cannot use use synchronize.</p><p><strong>Point E and Point D will be cover in second part with feature of locking framework</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f11af6b633f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ThreadPoolExecutor — Its behavior with Parameter]]></title>
            <link>https://ashwani-the-tiwari.medium.com/threadpoolexecutor-its-behavior-with-parameter-5e2979381b65?source=rss-d2dfb368cb55------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e2979381b65</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[threadpoolexecutor]]></category>
            <category><![CDATA[java-concurrency]]></category>
            <dc:creator><![CDATA[Ashwani tiwari]]></dc:creator>
            <pubDate>Wed, 14 Aug 2019 13:50:24 GMT</pubDate>
            <atom:updated>2019-08-14T13:50:24.496Z</atom:updated>
            <content:encoded><![CDATA[<h3>ThreadPoolExecutor — Its behavior with Parameter</h3><p>ThreadPoolExecutor is the class which extend the ExecutorService Interface.The ThreadPoolExecutor class used to create the executor which execute your task submitted to it. You can also create the executor using the Executors factory class provide by java.</p><p>But when you need some specific executor which is not provided by Executors class.Then you need to learn about the thread pool executor and its parameter from which you can create your own specific executor.</p><p>You take a look to is constructor in doc <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html">https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html</a></p><p>It provide four constructor , but we need only one to explain all the things</p><p><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html#ThreadPoolExecutor-int-int-long-java.util.concurrent.TimeUnit-java.util.concurrent.BlockingQueue-"><strong>ThreadPoolExecutor</strong></a>(int corePoolSize, int maximumPoolSize, long keepAliveTime, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/TimeUnit.html"><strong>TimeUnit</strong></a> unit, <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/BlockingQueue.html"><strong>BlockingQueue</strong></a>&lt;<a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html"><strong>Runnable</strong></a>&gt; workQueue)</p><p>As you can see in constructor — corePoolSize , maximumPoolSize , BlokingQueue. But I am not explain here about the what these field means , I am explaining here how u can create the executor using the above.</p><p>Now suppose</p><pre>   N = no of thread in currently in the pool.<br>   C = core size of pool<br>   M = maximum size of pool.<br>   BQ = Bounded Blocking Queue.(having a predefined capacity).<br>   UQ = Unbounded Blocking Queue.(without a predefined capacity).<br>   DHQ = Direct hand-offs Queue.</pre><p>Then</p><pre><strong>1. If BQ</strong><br><br>A. If N &lt;= C , then thread always created when task is         submitted, idle thread is  present in pool or not doesn&#39;t matter.</pre><pre>B. Once the core pool size is reached, executor start puting <br>   the new task in queue if there is no idle thread. <br>   If there is any idle thread then the task is assigned to idle thread.<br>           <br>C. When BQ is full, then executor start creating again new thread till its value reached to M if there is no idle thread.<br>So the new thread creation after reaching N=C value is start when queue is full.</pre><pre>D. Once N=M reached and BQ is also full , then executor not accept any task.It throw exception.</pre><pre><strong>2. If UQ </strong><br><br>   A. Same as above<br>   B. Same as above<br>   C. Not applicable. Why ? because it is unbounded queue.<br>      (UQ capacity is Integer.MAX_VALUE)<br>   D. No effect of M. Why ? Since creation of new thread again is start after the queue is full,but in the case UQ queue is never full. So new thread never created once reach N=C for the new task submitted. <br>Means thread in thread pool always be equal to C (N=C always) in case UQ , whatever the value of M<br><br><br><strong>3. If DHQ </strong></pre><pre> A. The direct hand-offs queue never put the task in queue, its immediately assigned task to thread if any thread is idle ,if not then it create new one.(task in queue is always 0)<br>          <br>B. The concept of C is not applicable in this queue.Thread created till its value reach M.</pre><pre>C. Once the N value reach M (N=M), and try to submit the task ,it reject the task.</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e2979381b65" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>