Sunday, August 9, 2015

File Locking in Java

NIO supports file locking to synchronize access to a file. You have the ability to lock a region of a file or the entire file. The file locking mechanism is handled by the operating system and therefore its exact effect is platform-dependent. On some operating systems, a file lock is advisory, whereas on some, it is mandatory. Since it is handled by the operating system, its effect is visible to other programs as well as to Java programs running in other JVMs. In this article, we try to understand this concept with the help of an example.


There are two kinds of file locking:

  1. Exclusive lock  : Only one program can hold an exclusive lock on a region of a file
  2. Shared lock : Multiple programs can hold shared locks on the same region of a file

You cannot mix an exclusive lock and a shared lock on the same region of a file. If a program has a shared lock on a region, another program must wait to get an exclusive lock on that region and vice versa. Some operating systems do not support a shared file lock, and in that case, the request for a shared file lock is converted to a request for an exclusive file lock.


How to represent File Lock
An object of the FileLock class, which is in the java.nio.channels package, represents a file lock. You acquire a lock on a file by using the lock() or tryLock() method of the FileChannel object

  • The lock() method blocks if the lock on the requested region of the file is not available
  • The tryLock() method does not block; it returns immediately. It returns an object of the FileLock class if the lock was acquired; otherwise, it returns null.


Versions of lock() and tryLock() methods
Both lock() and tryLock() methods have two versions: one without an argument and another with three arguments

  • The version without an argument locks the entire file.
  • The version with three arguments accepts the starting position of the region to lock, the number of bytes to lock, and a boolean flag to indicate if the lock is shared. The isShared() method of the FileLock object returns true if the lock is shared; otherwise, it returns false.



Different ways of obtaining locks on a file
The exception handling code is omitted for readability.

The file region that you lock may not be contained in the range of the file size. Suppose you have a file with a size of 100 bytes. When you request a lock on this file, you can specify that you want to lock a region of this file starting at byte 11 and covering 5000 bytes. Note that this file contains only 100 bytes; you are locking 5000 bytes. In such a case, if the file size grows beyond 100 bytes, your lock covers the additional region of the file. Suppose you locked 0 to 100 bytes of a 100-byte file. If this file grows to 150 bytes, your lock does not cover the last 50 bytes that was added after you acquired the lock.


The lock() and tryLock() methods of the FileChannel object, where you do not specify any argument, lock a region from 0 to Long.MAX_VALUE of the file. The two method calls fc.lock() and fc.lock(0, Long.MAX_VALUE, false) have the same effect


How to release the lock
When you are done with the file lock, you need to release it by using the release() method. 
A file lock is released in three ways:
by calling its release() method, by closing the file channel it is obtained from, and by shutting down the JVM. It is good practice to use a try-catch-finally block to acquire and release a file lock as follows:



Example
In this example, two thread will try to acquire the lock on the same file.

Sample output
File is locked by Thread-0
Thread-1 tried to acquire the lock
lock is released by Thread-0




If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...

64 comments:

  1. Hi,

    This is siva from Hyderabad.I am working on SEO Analyst.Your site was very good.i have one Idea.I have Google Adsense Account.i think you Don't have that Account.so I will give you my Adsense Account for your Site.if you have Intrested Please Contact Me my PH NO:09553267423...........


    Regards,
    Siva G.
    09553267423...........

    ReplyDelete
    Replies
    1. The internet today is full of SCAM ADS, mostly in comments of various sites and blogs. A large number of individuals have been victims of scam and lost a lot of money to SCAMMERS. Most of the common scam you can see
      ❌BANK LOAN SCAM. ❌BINARY OPTIONS SCAM.
      ❌BINARY AUCTION SCAM. ❌HACKING SCAM. and lost more......

      But here is a good news to everyone who has been a victim of INTERNET SCAM❗️
      You can get your money back from your scammer, Authorities will not been involve just the genius of our skill.

      WHO ARE WE⁉️
      We are PLUGGERS! A group of skilled Hackers and have dedicated our time to help individuals get back thier money from INTERNET SCAMMERS. There is a research was carried one to calculate the amount of money individual loose to Scam, and it was confirmed that more than USD $3billion annually. This is so wrong and that’s why we have decided to help individuals get thier money.

      HOW DO WE OPERATE⁉️
      We first of all study the scammer brought to us by hacking the person device(phone or computer) to get information of How, Where, this person keeps money he/she as defrauded from people ( so many of this scammers don’t actually save the money in banks, they mostly stack the money in a Bitcoin wallet, that way it is safe and untraceable to authorities) and we work on a strategy to get back the money and give it back to whom they have defrauded.

      Contacting us is simple, just give us a message through the email below.
      Email-: globalpluggers@gmail.com

      If you a victim of internet scam or you know someone who is, make contact to us immediately. You are 💯 % safe to contact us, our email is very secure.






      Delete



  2. I saw lot of information On Other Site But this blog helped me alot to learn Java Thanks for sharing.........

    ReplyDelete
  3. Very thanks to every one its too easy in to understanding thank u so much for this blog for gave valuable info to us.
    Thanks a lot! You made a new blog entry to answer my question; I really appreciate your time and effort.
    best java training in velachery |
    java training institute in chennai

    ReplyDelete
  4. Really great post, Thank you for sharing this knowledge. Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Sales and training programs. Please keep it up.

    ReplyDelete
  5. Hi
    I have read your blog its very attractive and impressive. I like it your blog.....
    java training in delhi

    ReplyDelete

  6. This is a great site for the modern architecture enthusiast. Plenty of dazzling photographs and just a plain neat blog..Want to build your own website
    White Label Website Builder

    ReplyDelete
  7. Thanks for sharing this information,this is useful to me...

    Core Java Online Training Hyderabad

    ReplyDelete
  8. Java is one of the most important element in each and every electronic device which helps in many activities. In java we have many different concepts with efficient to all the modules File Locking concept is a bit important and essential You have given an exact crystal clear approach to File Locking, When I was doing my PMP Training in Kuwait I was supposed to handle certain Java Projects in equal to other domains also Well Thank you so much for the Blog I will be looking forward for more and more updates from you.

    ReplyDelete
  9. Your concepts were easy to understand that I wondered why I never looked at it before. This information is definitely useful for everyone.
    You can also visit here Java training in delhi, java programming in delhi

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Woah this blog is wonderful i like studying your posts. Keep up the great work! You understand, lots of persons are hunting around for this info, you could help them greatly.
    python training Course in chennai
    python training in Bangalore
    Python training institute in kalyan nagar

    ReplyDelete
  12. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
    Best Devops Training in pune
    Devops Training in Chennai

    ReplyDelete
  13. Were a gaggle of volunteers as well as starting off a brand new gumption within a community. Your blog furnished us precious details to be effective on. You've got completed any amazing work!
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  14. Nice blog Content.It is very informative and helpful. Please share more content. Thanks.
    PHP Training in Gurgaon

    ReplyDelete

  15. An astounding web diary I visit this blog, it's inconceivably magnificent. Strangely, in this current blog's substance made point of fact and sensible. The substance of information is instructive.
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training
    oracle Fusion Technical online training

    ReplyDelete
  16. Excellent information by the author
    Best Play and Pre School for kids in Hyderabad,India. To give your kid a best environment and learning it is the right way to join in play and pre school were kids can build there physically, emotionally and mentally skills developed. We provide programs to kids like Play Group, Nursery, Sanjary Junior, Sanjary Senior and Teacher training Program.
    ­play school in hyderabad

    ReplyDelete
  17. Excellent blog information by the author

    Sanjary Academy is the best Piping Design institute in Hyderabad, Telangana. It is the best Piping design Course in India and we have offer professional Engineering Courses like Piping design Course, QA/QC Course, document controller course, Pressure Vessel Design Course, Welding Inspector Course, Quality Management Course and Safety Officer Course.
    Piping Design Course in India­

    ReplyDelete
  18. Good blog posts information

    Pressure Vessel Design Course is one of the courses offered by Sanjary Academy in Hyderabad. We have offer professional Engineering Course like Piping Design Course,QA / QC Course,document Controller course,pressure Vessel Design Course,Welding Inspector Course, Quality Management Course, #Safety officer course.
    Welding Inspector Course
    Safety officer course
    Quality Management Course
    Quality Management Course in India

    ReplyDelete
  19. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting this again.
    BCOM 1st, 2nd & Final Year Time Table 2020

    ReplyDelete
  20. The blog is very useful and informative which provides great information thanks for sharing this great information Checkpoint

    ReplyDelete
  21. Thank for this blog are more informative contents step by step. I here by attached my site would you see this blog.

    7 tips to start a career in digital marketing

    “Digital marketing is the marketing of product or service using digital technologies, mainly on the Internet, but also including mobile phones, display advertising, and any other digital medium”. This is the definition that you would get when you search for the term “Digital marketing” in google. Let’s give out a simpler explanation by saying, “the form of marketing, using the internet and technologies like phones, computer etc”.

    we have offered to the advanced syllabus course digital marketing for available join now.

    more details click the link now.

    https://www.webdschool.com/digital-marketing-course-in-chennai.html

    ReplyDelete
  22. Really great post, Thank you for sharing this knowledge.

    Web designing trends in 2020

    When we look into the trends, everything which is ruling today’s world was once a start up and slowly begun getting into. But Now they have literally transformed our lives on a tremendous note. To name a few, Facebook, Whats App, Twitter can be a promising proof for such a transformation and have a true impact on the digital world.

    we have offered to the advanced syllabus course web design and development for available join now.

    more details click the link now.

    https://www.webdschool.com/web-development-course-in-chennai.html

    ReplyDelete
  23. wonderful article.thanks for great blog. Our team manages all your social accounts and organized regular engaging social media campaigns so that your business is always creating a buzz on social media.

    digital marketing consultants in chennai | Leading digital marketing agencies in chennai | digital marketing agencies in chennai | Website designers in chennai

    ReplyDelete
  24. Nice Blog , I hope really i got lot of information for here to grow the career. thanks for sharing your idea.
    Java Online Training
    Python Online Training
    PHP Online Training

    ReplyDelete
  25. interesting piece of information, I had come to know about your web-page from my friend, i have read atleast eight posts of yours by now, and let me tell you, your blog gives the best and the most interesting information. This is just the kind of information that i had been looking for, i'm already your rss reader now and i would regularly watch out for the new posts, once again hats off to you! Thanks a million once again, Regards,
    Salesforce Training in Chennai | Certification | Online Course | Salesforce Training in Bangalore | Certification | Online Course | Salesforce Training in Hyderabad | Certification | Online Course | Salesforce Training in Pune | Certification | Online Course | Salesforce Online Training | Salesforce Training

    ReplyDelete
  26. wonderful article.with great blog post.River Group of Salon and spa, T.Nagar, provide a wide range of spa treatments, like body massage, scrub, wrap and beauty parlour services. We ensure unique care and quality service.

    massage in T.Nagar | body massage T.Nagar | massage spa in T.Nagar | body massage center in T.Nagar | massage centre in chennai | body massage in chennai | massage spa in chennai | body massage centre in chennai | full body massage in T.Nagar

    ReplyDelete
  27. Thanks for sharing this marvelous post. I m very pleased to read this article.
    Fashion bloggers in India

    ReplyDelete
  28. I am sure that this is going to help a lot of individuals. Keep up the good work. It is highly convincing and I enjoyed going through the entire blog.
    Java Training in Chennai

    Java Training in Velachery

    Java Training in Tambaram

    Java Training in Porur

    Java Training in OMR

    Java Training in Annanagar



    ReplyDelete
  29. Seo company in Varanasi, India : Best SEO Companies in Varanasi, India: Hire Kashi Digital Agency, best SEO Agency in varanasi, india, who Can Boost Your SEO Ranking, guaranteed SEO Services; Free SEO Analysis.

    Best Website Designing company in Varanasi, India : Web Design Companies in varanasi We design amazing website designing, development and maintenance services running from start-ups to the huge players


    Wordpress Development Company Varanasi, India : Wordpress development Company In varanasi, india: Kashi Digital Agency is one of the Best wordpress developer companies in varanasi, india. Ranked among the Top website designing agencies in varanasi, india. wordpress website designing Company.

    E-commerce Website designing company varanasi, India : Ecommerce website designing company in Varanasi, India: Kashi Digital Agency is one of the Best Shopping Ecommerce website designing agency in Varanasi, India, which provides you the right services.

    ReplyDelete
  30. Magnificent blog I visit this blog it's extremely wonderful. Interestingly, in this blog content composed plainly and reasonable. The substance of data is useful. We are also providing the best services click on below links to visit our website.
    Oracle Fusion HCM Training
    Workday Training
    Okta Training
    Palo Alto Training
    Adobe Analytics Training

    ReplyDelete
  31. One of the best blog spot I have ever seen. Reading this blog is make a curiosity to learn Programming. Keep up the good work.
    Core Java Training in Bangalore | Python Training in Bangalore | AWS Training in Bangalore

    ReplyDelete
  32. Hello, good article. Thanks for sharing this exciting blog. Good job. You may find my new article about CPS Test / CPS Tester interesting too. You can learn more about CPS Test- Click Per Second Mouse Click Speed Test Online by visiting this article. If you want to know more about CPS Test- Click Per Second Mouse Click Speed Test Online, read my article. Here we provide the number of clicks, the CPS test, and what the click count is. It is described in detail. This is very useful for beginners. See the article for more information.

    ReplyDelete
  33. Great article. Your blogs are unique and simple that is understood by anyone.

    BCA Time Table 2022

    ReplyDelete
  34. This comment has been removed by the author.

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. This comment has been removed by the author.

    ReplyDelete
  37. This blog is very attractive and impressive.
    visit: -swhizz

    ReplyDelete
  38. I see the best substance on your blog and I unbelievably love getting them.

    Python training institutions in hyderabad with real-time projects

    ReplyDelete
  39. Thank you for sharing this Blog, This is more informative and nice.

    Java Training in Hyderabad

    ReplyDelete
  40. informative blog , keep posting and dont forget to checkout our blog full stack course in satara

    ReplyDelete
  41. Fusion HCM Online Training
    course provides students with an overview of the various components of human resource management. It also provides an overview of each Oracle Fusion HCM Online module. The Fusion HCM course will cover topics such as creating users and permissions, managing employee data, and running reports. Thankful for your teaching & Guidance.

    ReplyDelete
  42. Thank you so much for sharing such an amazing information. Visit Instasource for Video Wall Display Suppliers in India, Active LED Display Distributor & Supplier in India, and Split Air Conditioners Suppliers in India at an affordable price.
    Video Wall Display Suppliers in India

    ReplyDelete