Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6572565
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T15:01:23+00:00 2026-05-25T15:01:23+00:00

In others words I don’t want a thread to wait if it cannot access

  • 0

In others words I don’t want a thread to wait if it cannot access the lock (as in synchonization), I want to thread execution to simply return immediately at that point if it cannot obtain the lock.

As simple boolean lock like this would potentially allow more than one thread to access.

private static boolean lockAvailable = true;

private boolean acquireLock() {
  if(lockAvailable) {
    lockAvailable = false;
    return true;
  }
  return false;
}

Am I missing something? What is the best/simplest way to achieve this?

Edit:

Thanks for pointing out Semaphore (!)

So looking at it again this code is bullet proof?

private final static Semaphore lock = new Semaphore(1, true);   

public void tryAndDoSomething() {
  if(lock.tryAcquire()) {
    try {
      // only single thread can access here at one time
    } finally {
      lock.release();
    }
  }
}

Update:

I realised I needed reentrant capability so I created a simple non blocking reentrant. Posting the code for anyone that is interested in how you might do this. Anyone who wants this type of functionality should of course use the existing Java Class java.util.concurrent.locks.ReentrantLock 😐

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * SimpleNonBlockingLock ensures that only a single thread can call protected code at any one time,
 * while allowing other threads to by pass the protected code if the lock is unavailable.
 * The thread owning the lock can access any code protected by the lock (the lock is 'reentrant').
 * To function correctly the protected code must be executed in a try/finally blocks. The
 * finally block must call the tryRelease. Example code:
 * 
 *  private final SimpleNonBlockingLock lock = new SimpleNonBlockingLock();
 * 
 *  if(lock.tryAcquire()) {
 *      try {
 *              // access protected code
 *      } finally {
 *          lock.tryRelease();
 *      }
 *  }
 *
 * This code is for demonstration only and should not be used. I have tested it and it 'seems to' work.
 * However it may contain horrific bugs!
 * 
 * The Java class java.util.concurrent.locks.ReentrantLock has been around since Java 5.0 and contains all (and more) 
 * of this functionality. Its also been thoroughly tested!
 */
public class SimpleNonBlockingLock {

    // Atomic locking mechanism
    private final AtomicBoolean locked = new AtomicBoolean();

    // Atomic integer containing the next thread ID to be assigned
    private static final AtomicInteger nextId = new AtomicInteger(0);

    // Unique ID of thread which currently has lock
    private int threadUniqueId = -1;

    // Tracks number of tryAcquire calls made by thread with lock
    private int lockCount = 0;

    // Thread local variable containing each thread's ID
    private static final ThreadLocal<Integer> threadId = new ThreadLocal<Integer>() {
            @Override protected Integer initialValue() {
                return nextId.getAndIncrement();
        }
    };

    public synchronized boolean tryAcquire() {      
        // Allow owning thread to acquire
        if(threadUniqueId == getCurrentThreadUniqueId()) {
            lockCount++;
            return true;
        }       
        // If locked then do not allow
        if (locked.get()) {return false;}           
        // Attempt to acquire lock      
        boolean attemptAcquire = locked.compareAndSet(false, true);     
        // If successful then set threadUniqueId for the thread, and increment lock count
        if(attemptAcquire) {
            threadUniqueId = getCurrentThreadUniqueId();
            lockCount++;
        }       
        // Return result of attempt to acquire lock
        return attemptAcquire;
    }

    public synchronized boolean tryRelease() {
        if (!locked.get()) {
            // Lock is currently available - no need to try and release
            return true;
        } else {
            // Decrement the lock count
            lockCount--;
            // If lock count is zero we release lock, and reset the threadUniqueId
            if(lockCount == 0) {
                threadUniqueId = -1;
                return locked.compareAndSet(true, false);
            } 
            return false;
        }   
    }

    // Returns the current thread's unique ID, assigning it if necessary
    public static int getCurrentThreadUniqueId() {      
        return threadId.get();
    }   
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T15:01:24+00:00Added an answer on May 25, 2026 at 3:01 pm

    Java 5 has introduced explicit locks which have a tryLock operation. So use an explicit lock instead of synchronized blocks, then you can call tryLock:

    private Lock lock = ...;
    
    private boolean acquireLock() {
      if (lock.tryLock()) {
          ...
          return true;
      } else {
          return false;
      }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In other words, is this Singleton implementation thread safe: public class Singleton { private
I want to try to convert a string to a Guid, but I don't
In other words: Are there any HTML constructs that don't allow certain elements to
In NHibernate, I want to retrieve an instance, and put an exclusive lock on
I'm trying to put together a regex to find when specific words don't exist
(Problem occur in Ubuntu only. Works fine in Windows. I don't know in other
In other words, a block of code like this: (setq initial-major-mode (lambda () (text-mode)
In other words, is it correct to use: public class CustomerList : System.Collections.Generic.List<Customer> {
In other words may one use /<tag[^>]*>.*?<\/tag>/ regex to match the tag html element
In other words, if I set up SSRS Express edition will I be able

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.