Java Multithreading, Thread.sleep pauses current thread but wont continue other threads

thread.sleep java
thread.sleep alternative java
java thread
thread.sleep in java for 1 minute
delay in java without using thread
java thread sleep vs wait
java thread wait
thread.sleep java 8

I'm practicing my self with Object Pool Design Pattern with Java. and created sample and tried to run my code.

Program provides limited number of Object in pool and run numbers of asynchronous processes.

My code simply pick up one object from pool (create new if there is no available and objects' count is less than the limit) and return if after Thread.sleep. but somehow other threads keeps on looping and couldn't find any available object.

public abstract class ObjectPool<T> {

    private long waitingTime;
    private int maxObjectPoolSize;

    private final List<T> available = Collections.synchronizedList(new ArrayList<>());
    private final List<T> inUse = Collections.synchronizedList(new ArrayList<>());

    protected AtomicInteger count = new AtomicInteger(0);
    private AtomicBoolean waiting = new AtomicBoolean(false);

    public abstract T create();

    public ObjectPool(int poolSize) {
        waitingTime = 1200;
        setMaxObjectPoolSize(poolSize);
    }

    public void setMaxObjectPoolSize(int poolSize) {
        this.maxObjectPoolSize = poolSize;
    }

    public synchronized T getObject() {
        if (!available.isEmpty()) {
            T o = available.remove(0);
            inUse.add(o);
            return o;
        }
        // if max pool size, wait for object to be released
        if(count.get() == maxObjectPoolSize) {
            this.waitUntilNextAvailable();
            return this.getObject();
        }
        // if no objects available, create new one
        T o = this.create();
        this.inUse.add(o);
        return o;
    }

    public synchronized void releaseObject(T o) {
        this.inUse.remove(o);
        this.available.add(o);
        System.out.println(o.toString() + " is free");
    }

    private void waitUntilNextAvailable() {
//        if (waiting.get()) {
//            waiting.set(false);
//            throw new ObjectNotFoundException("No Object Available");
//        }
//        waiting.set(true);
        System.out.println(Thread.currentThread().getName());
        waiting(waitingTime);
    }

    public void waiting(long ms) {
        try {
            TimeUnit.MILLISECONDS.sleep(ms);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }
}
public class ProcessThread implements Runnable {

    private RoomPool pool;

    public ProcessThread(RoomPool pool) {
        this.pool = pool;
    }

    @Override
    public void run() {
        takeAnObject();
    }

    private void takeAnObject() {
        try {
            System.out.println("New process: " + Thread.currentThread().getName());
            Room room = pool.getObject();

            TimeUnit.MILLISECONDS.sleep(randInt(1000, 1500));

            pool.releaseObject(room);
            System.out.println("executed: " + Thread.currentThread().getName());
        } catch (InterruptedException | ObjectNotFoundException e) {
            System.out.println(">>>> Process Rejected: " + Thread.currentThread().getName());
        }
    }

    private static int randInt(int min, int max) {
        return new Random().nextInt((max - min) + 1) + min;
    }
}
public class Main {

    public static final int OBJECT_POOL_SIZE = 4;

    public static final int NUMBER_OF_PROCESSES = 10;

    public static void main(String[] args) {
        RoomPool pool = new RoomPool(OBJECT_POOL_SIZE);
        for (int i = 1; i <= NUMBER_OF_PROCESSES; i++) {
            Runnable process = new ProcessThread(pool);
            Thread thread = new Thread(process);
            thread.start();
        }
    }
}

New process: Thread-5
New process: Thread-8
New process: Thread-3
New process: Thread-0
New process: Thread-4
New process: Thread-6
New process: Thread-7
New process: Thread-2
New process: Thread-1
New process: Thread-9
Room name = Room 1 is created
Room name = Room 2 is created
Room name = Room 3 is created
Room name = Room 4 is created
Thread-7
Thread-7
Thread-7
Thread-7
Thread-7
Thread-7

I can't figure out why the threads wont return the objects on pool.

I tried to debug it on my IDE and I saw after the thread being in SLEEP state, it goes to MONITOR after. I'm new to this multithreading thing so I don't know if this is normal.

Any help would be appreciated


You've made the ObjectPool's methods synchronized.

Meaning no thread can "release" an object (synchronized releaseObject(T o) if there is any thread already "getting" an object synchronized getObject().

Instead of making the whole methods synchronized, you should find a way to make just the modifications of inUse/available atomic.

Try removing the synchronized from the "getObject" and instead synchronize just the first addition/removal from the lists, like so:

public T getObject() {
    if (!available.isEmpty()) {
        synchronized(this) {
            T o = available.remove(0);
            inUse.add(o);
        }
        return o;
    }
    ....

Thread.sleep() in Java - Java Thread sleep, Thread.sleep() method can be used to pause the execution of current thread for There is another overloaded method sleep(long millis, int nanos) that can be used to package com.journaldev.threads; public class ThreadSleep { public static actual sleep statement, if you keep them one after the other, you won't see the� My code simply pick up one object from pool (create new if there is no available and objects' count is less than the limit) and return if after Thread.sleep. but somehow other threads keeps on looping and couldn't find any available object.


One thread is calling getObject() in a continuous recursion. Because this thread holds the lock on the pool (getObject() is synchronized), no thread can ever return an object to the pool (because releaseObject() is synchronized).

When implementing a pool, use concurrent data structures that do not block the release of resources. A release should always be non-blocking.

Difference between sleep() and wait() in Java, sleep() is a method which is used to pause the process for few seconds or the time we want to. But in case of wait() method, thread goes in waiting state and it won't t is a different thread; even then, it is the current thread that will sleep, wait() – when synchronized multiple threads access same Object� That means if the time expires and the joined thread has not completed, the current thread continues running normally. You can also join multiple threads with the current thread, for example: t1.join(); t2.join(); t3.join(); In this case, the current thread has to wait for all three threads t1, t2 and t3 completes before it can resume running.


Here the case of ojbect locking comes into the picture . when the thread(abc) will call the synchronized getobject() for n times . it will hold the lock so that until that time no thread will be able to access the synchronized getRelease() method. checkout the below ways to create the object pool.

OR

You can use java blocking Queue to create the object pool . blocking Queue is thread safe also.

OR

Refer below link to create the object pool https://dzone.com/articles/generic-and-concurrent-object

How to pause Thread in Java using Sleep() and TimeUnit Example , A thread blocked using wait() will remain to wait until the condition on which it is waiting Yes, you can put timeout there but the purpose of wait() method is different, they are By using sleep() method, you pause the current for some given time. If you are serious about mastering multi-threading and concurrency, I would� The above example consists of a for loop which iterates over the messages array, prints the current message, waits for 2 seconds by calling Thread.sleep(), and then proceeds with the next iteration. sleep() method throws InterruptedException if any thread interrupts the current thread. InterruptedException is a checked exception and it must be


Java Thread Primitive Deprecation, Stopping a thread causes it to unlock all the monitors that it has locked. these monitors were in an inconsistent state, other threads may now view these objects in an but it would vastly complicate the task of writing correct multithreaded code. currentThread(); while (blinker == thisThread) { try { Thread.sleep(interval ); }� Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.


Java Threads, Multithreading was designed into Java from the very beginning. public static void sleep(long millis, int nanos) throws InterruptedException {. A daemon thread is one that performs services for other threads, or periodically If a shared variable is in a register one thread won't be able to see another thread's change to it. Creating a thread. There are two ways to create a thread in java. First one is by extending the Thread class and second one is by implementing the Runnable interface. Let's see the examples of creating a thread.


Multithreading: What the methods of the Thread class do, Today we'll continue to talk about multithreading. Let's examine the Thread class and what a few of its methods do. Published in the Java Developer group Thread 's methods :) They have more complex logic that you won't be able execution of the current thread for a while, we use the sleep() method. MULTITHREADING in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other. Mulitple threads don't allocate separate memory area, hence they save