001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.backgroundtask;
016    
017    /**
018     * @author Michael C. Han
019     */
020    public class ClassLoaderAwareBackgroundTaskExecutor
021            extends DelegatingBackgroundTaskExecutor {
022    
023            public ClassLoaderAwareBackgroundTaskExecutor(
024                    BackgroundTaskExecutor backgroundTaskExecutor,
025                    ClassLoader classLoader) {
026    
027                    super(backgroundTaskExecutor);
028    
029                    _classLoader = classLoader;
030            }
031    
032            @Override
033            public BackgroundTaskExecutor clone() {
034                    BackgroundTaskExecutor backgroundTaskExecutor =
035                            new ClassLoaderAwareBackgroundTaskExecutor(
036                                    getBackgroundTaskExecutor(), _classLoader);
037    
038                    return backgroundTaskExecutor;
039            }
040    
041            @Override
042            public BackgroundTaskResult execute(BackgroundTask backgroundTask)
043                    throws Exception {
044    
045                    Thread currentThread = Thread.currentThread();
046    
047                    ClassLoader contextClassLoader = currentThread.getContextClassLoader();
048    
049                    if (_classLoader != contextClassLoader) {
050                            currentThread.setContextClassLoader(_classLoader);
051                    }
052    
053                    try {
054                            BackgroundTaskExecutor backgroundTaskExecutor =
055                                    getBackgroundTaskExecutor();
056    
057                            return backgroundTaskExecutor.execute(backgroundTask);
058                    }
059                    finally {
060                            if (_classLoader != contextClassLoader) {
061                                    currentThread.setContextClassLoader(contextClassLoader);
062                            }
063                    }
064            }
065    
066            private final ClassLoader _classLoader;
067    
068    }