php-lock / lock

Lock library to provide serialized execution of PHP code.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

No access to code return value in case of ExecutionOutsideLockException or LockReleaseException

Furgas opened this issue · comments

When LockReleaseException or ExecutionOutsideLockException is thrown there is no way to access the return value of the code block (it was executed).

Following change to LockMutex::synchronized() comes to mind:

    public function synchronized(callable $code)
    {
        $this->lock();

        $result = null;
        try {
            $result = $code();
        } finally {
	        try {
		        $this->unlock();
	        } catch (ExecutionOutsideLockException|LockReleaseException $e) {
		        $e->setCodeResult($result);
		        throw $e;
	        }
        }

        return $result;
    }

Also setCodeResult and getCodeResult should be added to both exception classes.

Of course a library user can always extend specific LockMutex subclass (ex. PredisMutex) and override the synchronized() method to deal with this problem, but maybe it's worth incorporating directly into the library.

It sounds nice @Furgas, would you be willing to create a PR?

Sure. Should I base it on master branch or develop (it's few commits behind master)?

On master would be great, thanks.

Created #29.

I am not quite sure if the solution is the right one.

Shouldn't exceptions be immutable? Meaning that if I pass around an exception, nobody should be able to modify the code result. Means that the code result should be already set in the constructor.

Regarding the case when the executed code threw an exception, wouldn't it make more sense to set that exception as previous exception when the LockReleaseException is thrown?

Regarding the case when the executed code threw an exception, wouldn't it make more sense to set that exception as previous exception when the LockReleaseException is thrown?

No, that should be the exception that caused the LockReleaseException. For example, a failure to execute the query to release the lock if a database server is used for storing locks.

There can be two exceptions: e.g. one is thrown by the code within the lock, then the lock is released, but that failed too.