Read Write Lock : Lock Synchronize « Threads « Java

Java
1. 2D Graphics GUI
2. 3D
3. Advanced Graphics
4. Ant
5. Apache Common
6. Chart
7. Class
8. Collections Data Structure
9. Data Type
10. Database SQL JDBC
11. Design Pattern
12. Development Class
13. EJB3
14. Email
15. Event
16. File Input Output
17. Game
18. Generics
19. GWT
20. Hibernate
21. I18N
22. J2EE
23. J2ME
24. JDK 6
25. JNDI LDAP
26. JPA
27. JSP
28. JSTL
29. Language Basics
30. Network Protocol
31. PDF RTF
32. Reflection
33. Regular Expressions
34. Scripting
35. Security
36. Servlets
37. Spring
38. Swing Components
39. Swing JFC
40. SWT JFace Eclipse
41. Threads
42. Tiny Application
43. Velocity
44. Web Services SOA
45. XML
Java Tutorial
Java Source Code / Java Documentation
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java » Threads » Lock SynchronizeScreenshots 
Read Write Lock
  
/*
 * Copyright 2002 (C) TJDO.
 * All rights reserved.
 *
 * This software is distributed under the terms of the TJDO License version 1.0.
 * See the terms of the TJDO License in the documentation provided with this software.
 *
 * $Id: ReadWriteLock.java,v 1.5 2006/08/02 22:41:25 jackknifebarber Exp $
 */



/**
 * A simple read-write lock implementation.  Multiple threads may lock using
 * readLock(), only one can lock using writeLock().  The caller is responsible
 * for coding a try-finally that ensures unlock() is called for every readLock()
 * and writeLock() call.
 *
 * <p>A ReadWriteLock is recursive; with one exception, a thread can re-lock an
 * object it already has locked.   Multiple read locks can be acquired by the
 * same thread, as can multiple write locks.  The exception however is that a
 * write lock cannot be acquired when a read lock is already held (to allow
 * this would cause deadlocks).
 *
 * <p>Successive lock calls from the same thread must be matched by an
 * equal number of unlock() calls.
 *
 @author <a href="mailto:mmartin5@austin.rr.com">Mike Martin</a>
 @version $Revision: 1.5 $
 */

public class ReadWriteLock
{
    private static final int WAIT_LOG_INTERVAL = 5000;

    /** A count for each thread indicating the number of read locks it holds. */
    private ThreadLocal readLocksByThread;

    /** The number of read locks held across all threads. */
    private int readLocks;

    /** The number of write locks held (by writeLockedBy). */
    private int writeLocks;

    /** The thread holding the write lock(s), if any. */
    private Thread writeLockedBy;


    /**
     * An object holding a per-thread read-lock count.
     */

    private static class Count
    {
        public int value = 0;
    }


    /**
     * Constructs read-write lock.
     */

    public ReadWriteLock()
    {
        readLocksByThread = new ThreadLocal()
            {
                public Object initialValue()
                {
                    return new Count();
                }
            };

        readLocks      = 0;
        writeLocks     = 0;
        writeLockedBy  = null;
    }


    /**
     * Acquire a read lock.  The calling thread will be suspended until no other
     * thread holds a write lock.
     *
     * <p>If the calling thread already owns a write lock for the object a read
     * lock is immediately acquired.
     *
     @exception InterruptedException
     *      If the thread is interrupted while attempting to acquire the lock.
     */

    public synchronized void readLock() throws InterruptedException
    {
        Thread me = Thread.currentThread();
        Count myReadLocks = (Count)readLocksByThread.get();

        if (writeLockedBy != me)
        {
            while (writeLocks > 0)
            {
                wait(WAIT_LOG_INTERVAL);

                if (writeLocks > 0)
                    System.out.println("Still waiting for read lock on ");
            }
        }

        ++readLocks;
        ++myReadLocks.value;
    }


    /**
     * Acquire a write lock.  The calling thread will be suspended until no
     * other thread holds a read or write lock.
     *
     * <p>This method cannot be called if the thread already owns a read lock on
     * the same ReadWriteLock object, otherwise an
     * <code>IllegalStateException</code> is thrown.
     *
     @exception IllegalStateException
     *      If the thread already holds a read lock on the same object.
     @exception InterruptedException
     *      If the thread is interrupted while attempting to acquire the lock.
     */

    public synchronized void writeLock() throws InterruptedException
    {
        Thread me = Thread.currentThread();
        Count myReadLocks = (Count)readLocksByThread.get();

        if (myReadLocks.value > 0)
            throw new IllegalStateException("Thread already holds a read lock");

        if (writeLockedBy != me)
        {
            while (writeLocks > || readLocks > 0)
            {
                wait(WAIT_LOG_INTERVAL);

                if (writeLocks > || readLocks > 0)
                    System.out.println("Still waiting for write lock on ");
            }

            writeLockedBy = me;
        }

        ++writeLocks;
    }


    /**
     * Release a read or write lock.  Must be called in a finally block after
     * acquiring a lock.
     */

    public synchronized void unlock()
    {
        Thread me = Thread.currentThread();
        Count myReadLocks = (Count)readLocksByThread.get();

        if (myReadLocks.value > 0)
        {
            --myReadLocks.value;
            --readLocks;
        }
        else if (writeLockedBy == me)
        {
            if (writeLocks > 0)
            {
                if (--writeLocks == 0)
                    writeLockedBy = null;
            }
        }

        notifyAll();
    }


    public String toString()
    {
        StringBuffer s = new StringBuffer(super.toString());

        s.append(": readLocks = ").append(readLocks)
         .append(", writeLocks = ").append(writeLocks)
         .append(", writeLockedBy = ").append(writeLockedBy);

        return s.toString();
    }
}

   
    
  
Related examples in the same category
1. Thread: Dining Philosophers
2. Synchronizing on another objectSynchronizing on another object
3. Operations that may seem safe are not, when threads are presentOperations that may seem safe are not, when threads are present
4. Synchronizing blocks instead of entire methodsSynchronizing blocks instead of entire methods
5. Boolean lockBoolean lock
6. Static synchronized blockStatic synchronized block
7. Thread notifyThread notify
8. Thread deadlockThread deadlock
9. Synchronize methodSynchronize method
10. Threads joinThreads join
11. Static synchronizeStatic synchronize
12. No synchronizeNo synchronize
13. Thread synchronizationThread synchronization
14. Synchronized Block demoSynchronized Block demo
15. Interruptible Synchronized Block Interruptible Synchronized Block
16. SignalingSignaling
17. Simple Object FIFOSimple Object FIFO
18. Object FIFOObject FIFO
19. Byte FIFOByte FIFO
20. Thread Synch
21. Daemon Lock
22. Determining If the Current Thread Is Holding a Synchronized Lock
23. Handle concurrent read/write: use synchronized to lock the data
24. Lock for read and write
25. Coordinates threads for multi-threaded operations
26. A reader-writer lock from "Java Threads" by Scott Oak and Henry Wong.
27. Invoke a series of runnables as closely to synchronously as possible
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.