ketan
ketan

Reputation: 2904

java LinkedList's LinkedList.isEmpty() method not working properly?

Actually, I'm using one thread to insert elements in one LinkedList and another thread to remove these elements from the LinkedList(). Before removing I want to check is LinkedList contains element or not so I'm using LinkedList.isEmpty() method but it is not working as I'm expecting. I want to know reason behind that!

Here is my sample code:

import java.util.LinkedList;

public class Demo {

    private LinkedList li;

    private Demo() {
        li = new LinkedList();
    }

    public void insert() {
        for (int i = 0; i <= 100; i++) {
            li.add(i);
            System.out.println("inserted : " + i);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

    public void remove() {
        while (true) {
            if (li.isEmpty()) {
                //System.out.println("this statement has no significance..."); // Line Number 27
            } else {
                int a = (int) li.poll();
                System.out.println("removed : " + a);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        final Demo main = new Demo();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                main.insert();
            }
        };
        t1.start();

        Thread t2 = new Thread() {
            @Override
            public void run() {
                main.remove();
            }
        };
        t2.start();
        while (true) {

        }
    }

}

My Observations:

Upvotes: 1

Views: 1739

Answers (1)

OldCurmudgeon
OldCurmudgeon

Reputation: 65859

For this kind of functionality you should use a thread-safe structure such as a BlockingQueue. Specifically you could use the poll(long,TimeUnit) method.

The reason adding the sop fixes the issue is that it adds a small delay each time around the loop. If there is no delay you are effectively spinning in a tight loop without giving the JVM any opportunity to switch threads.

Upvotes: 1

Related Questions