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:
Can someone please explain?
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.
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.
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.
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);
}
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 lock
ed before making any change to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With