protected LockSupplier getLockSupplier()

in deltaspike/core/impl/src/main/java/org/apache/deltaspike/core/impl/lock/LockSupplierStorage.java [53:122]


    protected LockSupplier getLockSupplier(final InvocationContext ic)
    {
        final Method key = ic.getMethod();
        LockSupplier operation = lockSuppliers.get(key);
        if (operation == null)
        {
            final Class declaringClass = key.getDeclaringClass();
            final AnnotatedType<Object> annotatedType = beanManager.createAnnotatedType(declaringClass);
            final AnnotatedMethod<?> annotatedMethod = AnnotatedMethods.findMethod(annotatedType, key);

            Locked config = annotatedMethod.getAnnotation(Locked.class);
            if (config == null)
            {
                config = annotatedType.getAnnotation(Locked.class);
            }
            final Locked.LockFactory factory = config.factory() != Locked.LockFactory.class ?
                    Locked.LockFactory.class.cast(
                            beanManager.getReference(beanManager.resolve(
                                    beanManager.getBeans(
                                            config.factory())),
                                    Locked.LockFactory.class, null)) : this;

            final ReadWriteLock writeLock = factory.newLock(annotatedMethod, config.fair());
            final long timeout = config.timeoutUnit().toMillis(config.timeout());
            final Lock lock = config.operation() == READ ? writeLock.readLock() : writeLock.writeLock();

            if (timeout > 0)
            {
                operation = new LockSupplier()
                {
                    @Override
                    public Lock get()
                    {
                        try
                        {
                            if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS))
                            {
                                throw new IllegalStateException("Can't lock for " + key + " in " + timeout + "ms");
                            }
                        }
                        catch (final InterruptedException e)
                        {
                            Thread.interrupted();
                            throw new IllegalStateException("Locking interrupted", e);
                        }
                        return lock;
                    }
                };
            }
            else
            {
                operation = new LockSupplier()
                {
                    @Override
                    public Lock get()
                    {
                        lock.lock();
                        return lock;
                    }
                };
            }

            final LockSupplier existing = lockSuppliers.putIfAbsent(key, operation);
            if (existing != null)
            {
                operation = existing;
            }
        }
        return operation;
    }