0

I need lock a function from another function in java. In example above, I call slave function to print counter. And I need when that if master function called, all threads which calls slave function must be wait master functions to be ended.

How can I do that?

int counter = 0;

private void slave()
{
  System.out.println(counter);
}

private void master()
{
  lockSlave();
  counter ++;
  unlockSlave();
}
3
  • You really don't need any locks for this particular task. Consider using AtomicInteger or LongAdder Commented Mar 29, 2016 at 9:05
  • It's just an example you know. In real slave function in my repository includes a lot of complex algorithms, not basic counter. @SashaSalauyou Commented Mar 29, 2016 at 11:15
  • Yes I understand. Just tried to put your attention to another JDK components that are extremely useful in concurrency programming. Commented Mar 29, 2016 at 11:19

3 Answers 3

2

Take a look at JDK ReentrantReadWriteLock.

private final ReadWriteLock lock = new ReentrantReadWriteLock();

private void slave()
{
    lock.readLock().lock();
    try {
        System.out.println(counter);
        ...
    } finally {
        lock.readLock().unlock();
    }
}

private void master()
{
    lock.writeLock().lock();
    try {
        counter ++;
        ...
    } finally {
        lock.writeLock().unlock();
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

if counter is thread-safe, no lock is needed. If the lock is acquired for every counter++, it doesn't need to be thread-save nor volatile
2

Use a ReentrantReadWriteLock. Also make your variable volatile so changes can be seen by all threads.

ReadWriteLock m_lock = new ReentrantReadWriteLock();
Lock m_readLock = m_lock.readLock();
Lock m_writeLock = m_lock.writeLock();

volatile int counter = 0;

private void slave() {
  m_readLock.lock();
  try {
    System.out.println(counter);
  } finally {
    m_readLock.unlock();
  }
}

private void master(){
  m_writeLock.lock();
  try {
    counter ++;
  } finally {
    m_writeLock.unlock();
  }
}

1 Comment

the common idiom is to acquire a lock before try, not inside it, see: docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/… As .lock() itself may throw, after which you'll get an exception in finally
-1

Use synchronized word, is what is for, you can synchronize the full method, so only one thread will be able to run at once.

1 Comment

That's true. But but synchronized only "locks" one method, the question is about two different methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.