Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack Empty Exception

I am getting a stack empty exception. How is that possible if the stack is not empty (it has 16 items)?

I got a snap shot of the error:

Stack Empty Exception

Can someone please explain?

like image 221
Ibrahim Ahmed Avatar asked Jan 02 '13 12:01

Ibrahim Ahmed


People also ask

How do you throw an empty stack exception?

The pop() method checks to see if there are any elements on the stack. If the stack is empty (its size is equal to 0) then pop() instantiates a new EmptyStackException object and throws it.

Does stack have isEmpty?

isEmpty() method in Java is used to check and verify if a Stack is empty or not. It returns True if the Stack is empty else it returns False.

What is the role of stack in exception handling in Java?

When you see a Java application throw an exception, you usually see a stack trace logged with it. This is because of how exceptions work. When Java code throws an exception, the runtime looks up the stack for a method that has a handler that can process it. If it finds one, it passes the exception to it.


2 Answers

You must synchronize access when using something like Stack<T>. The simplest approach is to use lock, which then also let's you use the lock for the synchronization itself; so pop would be:

int item;
lock (SharedMemory)
{
    while (SharedMemory.Count == 0)
    {
        Monitor.Wait(SharedMemory);
    }
    item = SharedMemory.Pop();
}
Console.WriteLine(item);

and push would be:

lock (SharedMemory)
{
    SharedMemory.Push(item);
    Monitor.PulseAll(SharedMemory);
}
like image 79
Marc Gravell Avatar answered Oct 05 '22 22:10

Marc Gravell


how is that possible the stack is full & has 16 items??!

In multithreading environment it is very much possible.

Are you using more than one threads in your program? If yes, SharedMemory should be locked before making any change to it.

like image 33
Azodious Avatar answered Oct 06 '22 00:10

Azodious