Skip to content

@WriteLock @ReadLock

peichhorn edited this page Jun 30, 2012 · 6 revisions

@ReadLock and @WriteLock

Overview

(Documentation pending)

Example

With Lombok

import lombok.ReadLock;
import lombok.WriteLock;

import java.util.HashMap;
import java.util.Map;

public class LockExample {
  private Map<String, String> dictionary = new HashMap<String, String>();
  
  @WriteLock("dictionaryLock")
  public void put(String key, String value) {
    dictionary.put(key, value);
  }

  @ReadLock("dictionaryLock")
  public String get(String key) {
    return dictionary.get(key);
  }
}

Vanilla Java

import java.util.Map;
import java.util.HashMap;

class LockExample {
  private final java.util.concurrent.locks.ReadWriteLock dictionaryLock = new java.util.concurrent.locks.ReentrantReadWriteLock();
  private Map<String, String> dictionary = new HashMap<String, String>();

  public void put(final String key, final String value) {
    this.dictionaryLock.writeLock().lock();
    try {
      dictionary.put(key, value);
    } finally {
      this.dictionaryLock.writeLock().unlock();
    }
  }

  public String get(final String key) {
    this.dictionaryLock.readLock().lock();
    try {
      return dictionary.get(key);
    } finally {
      this.dictionaryLock.readLock().unlock();
    }
  }
}

Behind the Scenes

(Documentation pending)

Configuration

Nothing to configure yet.


Clone this wiki locally