001/*
002 * (C) Copyright 2013 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl-2.1.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Florent Guillaume
016 */
017package org.nuxeo.ecm.core.work;
018
019import java.util.concurrent.ThreadPoolExecutor;
020
021import org.nuxeo.ecm.core.work.api.Work;
022import org.nuxeo.runtime.trackers.concurrent.ThreadEvent;
023
024/**
025 * A {@link WorkHolder} adapts a {@link Work} to {@link Runnable} for queuing and execution by a
026 * {@link ThreadPoolExecutor}.
027 * <p>
028 * Calls (indirectly) {@link Work#work} and {@link Work#cleanUp}.
029 *
030 * @see Work
031 * @see Work#work
032 * @see Work#cleanUp
033 * @see AbstractWork
034 * @since 5.8
035 */
036public class WorkHolder implements Runnable {
037
038    private final Work work;
039
040    public WorkHolder(Work work) {
041        this.work = work;
042    }
043
044    public static Work getWork(Runnable r) {
045        return ((WorkHolder) r).work;
046    }
047
048    @Override
049    public void run() {
050        ThreadEvent.onEnter(this, false).send();
051        try {
052            work.run();
053        } finally {
054            ThreadEvent.onLeave(this).send();
055        }
056    }
057
058}