I have a class that exposes two methods:
- GetObject
Gets a single object, or returns null if there are none.
- WaitForObject
Gets a single object, or waits until their is one.
An example implementation:
class MyClass
{
MyStack stack;
public object GetObject()
{
return stack.Pop();
}
public object WaitForObject()
{
object returnValue;
while (returnValue == null)
returnValue = stack.Pop()
return returnValue
}
}
With the assumption that MyStack
is thread safe, how can I make MyClass
thread safe? I.e.
- GetObject
should never block
- Thread
doing WaitForObject
should get any new objects added to the stack instead of GetObject
.
For bonus points, how can users adding objects to the stack notify any listeners that a new object is available? (eliminating the need for polling)