Example usage for java.lang ThreadLocal ThreadLocal

List of usage examples for java.lang ThreadLocal ThreadLocal

Introduction

In this page you can find the example usage for java.lang ThreadLocal ThreadLocal.

Prototype

public ThreadLocal() 

Source Link

Document

Creates a thread local variable.

Usage

From source file:biz.c24.io.spring.batch.processor.C24TransformItemProcessor.java

/**
 * Turn validation on or off/*from ww w  .  j  a v  a2 s .c om*/
 * 
 * @param validate 
 */
public void setValidation(boolean validate) {
    validator = validate ? new ThreadLocal<ValidationManager>() : null;
}

From source file:hudson.plugins.clearcase.AbstractClearCaseScm.java

private synchronized ThreadLocal<String> getNormalizedViewPathThreadLocalWrapper() {
    if (normalizedViewPath == null) {
        normalizedViewPath = new ThreadLocal<String>();
    }//from w ww . j a  va2s. com
    return normalizedViewPath;
}

From source file:module.siadap.domain.SiadapRootModule.java

@Atomic
public synchronized static void initialize() {
    if (!isInitialized) {
        try {/* ww w. j a va 2s  .  c  o  m*/
            final Bennu bennu = Bennu.getInstance();
            final SiadapRootModule system = bennu.getSiadapRootModule();
            if (system == null) {
                new SiadapRootModule();
            }
            init = new ThreadLocal<SiadapRootModule>();
            init.set(bennu.getSiadapRootModule());

            isInitialized = true;
        } finally {
            init = null;
        }
    }

}

From source file:org.lightadmin.core.persistence.repository.event.FileManipulationRepositoryEventListener.java

private static ThreadLocal<FileReferenceProperties> newFileItemsContext() {
    return new ThreadLocal<FileReferenceProperties>() {
        protected FileReferenceProperties initialValue() {
            return new FileReferenceProperties();
        }//ww  w.java2 s. co m
    };
}

From source file:com.espertech.esper.core.EPRuntimeImpl.java

/**
 * Constructor.//from   w  w  w  .j  av a  2  s  . co  m
 * @param services - references to services
 */
public EPRuntimeImpl(final EPServicesContext services) {
    this.services = services;
    this.threadWorkQueue = new ThreadWorkQueue();
    isLatchStatementInsertStream = this.services.getEngineSettingsService().getEngineSettings().getThreading()
            .isInsertIntoDispatchPreserveOrder();
    isUsingExternalClocking = !this.services.getEngineSettingsService().getEngineSettings().getThreading()
            .isInternalTimerEnabled();
    isSubselectPreeval = services.getEngineSettingsService().getEngineSettings().getExpression()
            .isSelfSubselectPreeval();
    isPrioritized = services.getEngineSettingsService().getEngineSettings().getExecution().isPrioritized();
    routedInternal = new AtomicLong();
    routedExternal = new AtomicLong();
    engineFilterAndDispatchTimeContext = new ExprEvaluatorContext() {
        private ExpressionResultCacheService expressionResultCacheService = new ExpressionResultCacheService();

        public TimeProvider getTimeProvider() {
            return services.getSchedulingService();
        }

        public ExpressionResultCacheService getExpressionResultCacheService() {
            return expressionResultCacheService;
        }
    };

    matchesPerStmtThreadLocal = new ThreadLocal<Map<EPStatementHandle, ArrayDeque<FilterHandleCallback>>>() {
        protected synchronized Map<EPStatementHandle, ArrayDeque<FilterHandleCallback>> initialValue() {
            if (isPrioritized) {
                return new TreeMap<EPStatementHandle, ArrayDeque<FilterHandleCallback>>(
                        new Comparator<EPStatementHandle>() {
                            public int compare(EPStatementHandle o1, EPStatementHandle o2) {
                                if (o1 == o2) {
                                    return 0;
                                }
                                if (o1.equals(o2)) {
                                    return 0;
                                }
                                return o1.getPriority() >= o2.getPriority() ? -1 : 1;
                            }
                        });
            } else {
                return new HashMap<EPStatementHandle, ArrayDeque<FilterHandleCallback>>(10000);
            }
        }
    };

    schedulePerStmtThreadLocal = new ThreadLocal<Map<EPStatementHandle, Object>>() {
        protected synchronized Map<EPStatementHandle, Object> initialValue() {
            if (isPrioritized) {
                return new TreeMap<EPStatementHandle, Object>(new Comparator<EPStatementHandle>() {
                    public int compare(EPStatementHandle o1, EPStatementHandle o2) {
                        if (o1 == o2) {
                            return 0;
                        }
                        if (o1.equals(o2)) {
                            return 0;
                        }
                        return o1.getPriority() >= o2.getPriority() ? -1 : 1;
                    }
                });
            } else {
                return new HashMap<EPStatementHandle, Object>(10000);
            }
        }
    };

    services.getThreadingService().initThreading(services, this);
}

From source file:biz.c24.io.spring.batch.processor.C24TransformItemProcessor.java

/**
 * Releases any transient state left over from this transformation step
 *///from   w ww.  j  ava 2  s  . c o  m
@AfterStep
public void cleanup() {
    // Release any validation managers we're holding; no guarantee the same thread pool will be used next time
    if (validator != null) {
        validator = new ThreadLocal<ValidationManager>();
    }
}

From source file:com.mmnaseri.dragonfly.data.impl.DefaultDataAccessSession.java

public DefaultDataAccessSession(DatabaseDialect databaseDialect, StatementRegistry statementRegistry,
        TableMetadataRegistry tableMetadataRegistry, DataSource dataSource, String username, String password) {
    loadDriver(databaseDialect);/*from  w  w w .j  av  a  2s. c o m*/
    this.databaseDialect = databaseDialect;
    this.statementRegistry = statementRegistry;
    this.tableMetadataRegistry = tableMetadataRegistry;
    this.dataSource = dataSource;
    this.username = username;
    this.password = password;
    this.dataStructureHandler = new DefaultDataStructureHandler(this, tableMetadataRegistry);
    this.localConnection = new ThreadLocal<DelegatingConnection>();
}

From source file:com.android.launcher2.AsyncTaskCallback.java

public WeakReferenceThreadLocal() {
    mThreadLocal = new ThreadLocal<WeakReference<T>>();
}

From source file:com.blackducksoftware.integration.hub.jenkins.gradle.GradleBuildWrapper.java

@Override
public Environment setUp(final AbstractBuild build, final Launcher launcher, final BuildListener listener)
        throws IOException, InterruptedException {
    // no failure to report yet
    final HubJenkinsLogger buildLogger = new HubJenkinsLogger(listener);
    buildLogger.setLogLevel(LogLevel.TRACE);
    Gradle gradleBuilder = null;/*www. j  ava 2 s. c om*/
    if (build.getProject() instanceof FreeStyleProject) {
        // Project should always be a FreeStyleProject, thats why we have the isApplicable() method
        final List<Builder> builders = ((FreeStyleProject) build.getProject()).getBuilders();

        if (builders == null || builders.isEmpty()) {
            // User didn't configure the job with a Builder
            buildLogger.error("No Builder found for this job.");
            buildLogger.error("Will not run the Hub Gradle Build wrapper.");
            build.setResult(Result.UNSTABLE);
            return new Environment() {
            }; // Continue with the rest of the Build
        }

        for (final Builder builder : builders) {
            if (builder instanceof Gradle) {
                gradleBuilder = (Gradle) builder;
            }
        }
        if (gradleBuilder == null) {
            // User didn't configure the job with a Gradle Builder
            buildLogger.error("This Wrapper should be run with a Gradle Builder");
            buildLogger.error("Will not run the Hub Gradle Build wrapper.");
            build.setResult(Result.UNSTABLE);
            return new Environment() {
            }; // Continue with the rest of the Build
        }
    } else {
        buildLogger.error("Cannot run the Hub Gradle Build Wrapper for this type of Project.");
        build.setResult(Result.UNSTABLE);
        return new Environment() {
        }; // Continue with the rest of the Build
    }
    if (validateConfiguration(buildLogger)) {
        buildLogger.info("Build Recorder enabled");
        buildLogger.info("Hub Jenkins Plugin version : " + getDescriptor().getPluginVersion());

    } else {
        build.setResult(Result.UNSTABLE);
        return new Environment() {
        }; // Continue with the rest of the Build
    }

    final ThreadLocal<String> originalSwitches = new ThreadLocal<String>();
    final ThreadLocal<String> originalTasks = new ThreadLocal<String>();

    if (gradleBuilder != null) {

        originalSwitches.set(gradleBuilder.getSwitches() + "");
        originalTasks.set(gradleBuilder.getTasks() + "");

        final BDGradleInitScriptWriter writer = new BDGradleInitScriptWriter(build, buildLogger);
        final FilePath workspace = build.getWorkspace();
        FilePath initScript;
        String initScriptPath;
        try {
            if (workspace == null) {
                buildLogger.error("Workspace: null");
            } else {
                initScript = workspace.createTextTempFile("init-blackduck", "gradle",
                        writer.generateInitScript(), false);
                if (initScript != null) {
                    initScriptPath = initScript.getRemote();
                    initScriptPath = initScriptPath.replace('\\', '/');

                    String newSwitches = originalSwitches.get();
                    String newTasks = originalTasks.get();

                    if (!originalSwitches.get().contains("--init-script ")
                            && !originalSwitches.get().contains("init-blackduck")) {
                        newSwitches = newSwitches + " --init-script " + initScriptPath;
                    }
                    if (!originalSwitches.get().contains(" -D" + BDGradleUtil.BUILD_ID_PROPERTY)) {
                        newSwitches = newSwitches + " -D" + BDGradleUtil.BUILD_ID_PROPERTY + "="
                                + build.getId();
                    }
                    if (!originalSwitches.get()
                            .contains(" -D" + BDGradleUtil.INCLUDED_CONFIGURATIONS_PROPERTY)) {
                        String configurations = getUserScopesToInclude();
                        configurations = configurations.replaceAll(" ", "");

                        newSwitches = newSwitches + " -D" + BDGradleUtil.INCLUDED_CONFIGURATIONS_PROPERTY + "="
                                + configurations;
                    }
                    // // Following used to generate the dependency tree
                    // // written to a file
                    // if (!originalSwitches.get().contains(" -D" +
                    // BDGradleUtil.DEPENDENCY_REPORT_OUTPUT)) {
                    // FilePath dependencyTreeFile = new FilePath(workspace, "dependencyTree.txt");
                    // newSwitches = newSwitches + " -D" +
                    // BDGradleUtil.DEPENDENCY_REPORT_OUTPUT + "='" +
                    // dependencyTreeFile.getRemote() + "'";
                    // }

                    if (!originalTasks.get().contains("bdCustomTask")) {
                        newTasks = newTasks + " bdCustomTask";
                    }

                    if (!originalTasks.get().contains("bdDependencyTree")) {
                        newTasks = newTasks + " bdDependencyTree";
                    }
                    setField(gradleBuilder, "switches", newSwitches);
                    setField(gradleBuilder, "tasks", newTasks);
                }
            }
        } catch (final Exception e) {
            listener.getLogger().println("Error occurred while writing Gradle Init Script: " + e.getMessage());
            build.setResult(Result.FAILURE);
        }

    }

    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    boolean changed = false;
    try {
        if (GradleBuildWrapper.class.getClassLoader() != originalClassLoader) {
            changed = true;
            Thread.currentThread().setContextClassLoader(GradleBuildWrapper.class.getClassLoader());
        }
        return new Environment() {
            @Override
            public boolean tearDown(final AbstractBuild build, final BuildListener listener)
                    throws IOException, InterruptedException {
                final HubJenkinsLogger buildLogger = new HubJenkinsLogger(listener);
                Gradle gradleBuilder = null;
                try {
                    if (build.getProject() instanceof FreeStyleProject) {
                        // Project should always be a FreeStyleProject, thats why we have the isApplicable() method
                        final List<Builder> builders = ((FreeStyleProject) build.getProject()).getBuilders();

                        for (final Builder builder : builders) {
                            if (builder instanceof Gradle) {
                                gradleBuilder = (Gradle) builder;
                            }
                        }
                    }
                    if (gradleBuilder != null) {
                        String rootBuildScriptDir = gradleBuilder.getRootBuildScriptDir();

                        if (StringUtils.startsWithIgnoreCase(rootBuildScriptDir, "${WORKSPACE}")
                                || StringUtils.startsWithIgnoreCase(rootBuildScriptDir, "$WORKSPACE")) {
                            final EnvVars variables = build.getEnvironment(listener);
                            rootBuildScriptDir = BuildHelper.handleVariableReplacement(variables,
                                    rootBuildScriptDir);
                        }

                        String fileSeparator = null;
                        try {
                            final VirtualChannel channel = build.getBuiltOn().getChannel();
                            if (channel == null) {
                                buildLogger.error("Channel build on: null");
                            } else {
                                fileSeparator = channel.call(new GetSeparator());
                            }
                        } catch (final IOException e) {
                            buildLogger.error(e.toString(), e);
                        } catch (final InterruptedException e) {
                            buildLogger.error(e.toString(), e);
                        }
                        if (StringUtils.isEmpty(fileSeparator)) {
                            fileSeparator = File.separator;
                        }

                        File workspaceFile = null;
                        if (build.getWorkspace() == null) {
                            // might be using custom workspace
                            workspaceFile = new File(build.getProject().getCustomWorkspace());
                        } else {
                            workspaceFile = new File(build.getWorkspace().getRemote());
                        }

                        String workingDirectory = "";
                        try {
                            workingDirectory = build.getBuiltOn().getChannel()
                                    .call(new GetCanonicalPath(workspaceFile));
                        } catch (final IOException e) {
                            buildLogger.error("Problem getting the working directory on this node. Error : "
                                    + e.getMessage(), e);
                        }

                        if (!StringUtils.startsWithIgnoreCase(rootBuildScriptDir, workingDirectory)) {
                            if (workingDirectory.endsWith(fileSeparator)) {
                                rootBuildScriptDir = workingDirectory + rootBuildScriptDir;
                            } else {
                                rootBuildScriptDir = workingDirectory + fileSeparator + rootBuildScriptDir;
                            }
                        }

                        FilePath buildInfo = null;
                        final Node buildOn = build.getBuiltOn();
                        if (buildOn == null) {
                            buildLogger.error("Node build on: null");
                        } else {
                            final VirtualChannel channel = buildOn.getChannel();
                            if (channel == null) {
                                buildLogger.error("Channel build on: null");
                            } else {
                                // buildInfoFile = new FilePath(channel, workspacePath);
                                buildInfo = new FilePath(channel, rootBuildScriptDir);
                                buildInfo = new FilePath(buildInfo, "build");
                                buildInfo = new FilePath(buildInfo, "BlackDuck");
                                buildInfo = new FilePath(buildInfo, BuildInfo.OUTPUT_FILE_NAME);

                            }
                        }

                        if (buildInfo != null) {

                            if (buildInfo.exists()) {
                                return universalTearDown(build, buildLogger, buildInfo, getDescriptor(),
                                        BuilderType.GRADLE);
                            } else {
                                buildLogger.error(
                                        "The " + BuildInfo.OUTPUT_FILE_NAME + " file does not exist at : "
                                                + buildInfo.getRemote() + ", on machine : "
                                                + (buildOn == null ? "null" : buildOn.getDisplayName()));
                                build.setResult(Result.UNSTABLE);
                                return true;
                            }
                        }
                        // }
                    } else {
                        buildLogger.error("[WARNING] no gradle build step found");
                        build.setResult(Result.UNSTABLE);
                        return true;
                    }
                } catch (final BDJenkinsHubPluginException e) {
                    buildLogger.error(e.getMessage(), e);
                    build.setResult(Result.UNSTABLE);
                    return true;
                } catch (final Exception e) {
                    buildLogger.error(e.getMessage(), e);
                    build.setResult(Result.UNSTABLE);
                    return true;
                } finally {
                    if (gradleBuilder != null) {
                        synchronized (this) {
                            try {
                                // restore the original configuration
                                setField(gradleBuilder, "switches", originalSwitches.get());
                                setField(gradleBuilder, "tasks", originalTasks.get());
                            } catch (final Exception e) {
                                buildLogger.error(e.getMessage(), e);
                                build.setResult(Result.UNSTABLE);
                                return true;
                            }
                        }
                    }
                }
                return true;
            }
        };
    } finally {
        if (changed) {
            Thread.currentThread().setContextClassLoader(originalClassLoader);
        }
    }
}

From source file:com.strategicgains.docussandra.controller.perf.remote.parent.PerfTestParent.java

public void loadData() throws IOException, ParseException, InterruptedException {
    logger.info("------------Loading Data into: " + this.getDb().name() + " with Docussandra!------------");
    ArrayList<Thread> workers = new ArrayList<>(NUM_WORKERS + 1);
    int numDocs = getNumDocuments();
    int docsPerWorker = numDocs / NUM_WORKERS;
    try {//from  w ww. j av  a  2 s .c  o m
        List<Document> docs = getDocumentsFromFS();
        ArrayList<List<Document>> documentQueues = new ArrayList<>(NUM_WORKERS + 1);
        int numDocsAssigned = 0;
        while ((numDocsAssigned + 1) < numDocs) {
            int start = numDocsAssigned;
            int end = numDocsAssigned + docsPerWorker;
            if (end > numDocs) {
                end = numDocs - 1;
            }
            documentQueues.add(new ArrayList(docs.subList(start, end)));
            numDocsAssigned = end;
        }
        for (final List<Document> queue : documentQueues) {
            workers.add(new Thread() {
                @Override
                public void run() {
                    for (Document d : queue) {
                        //logger.debug("Processing document: " + d.toString());
                        postDocument(getDb(), getTb(), d);
                    }
                    logger.info("Thread " + Thread.currentThread().getName() + " is done.");
                }
            });
        }
    } catch (UnsupportedOperationException e)//we can't read everything in at once
    {
        //all we need to do in this block is find a way to set "workers"
        for (int i = 0; i < NUM_WORKERS; i++) {
            workers.add(new Thread() {
                private final int chunk = (int) (Math.random() * 100) + 150;//pick a random chunk so we are not going back to the FS all at the same time and potentially causing a bottle neck

                @Override
                public void run() {
                    ThreadLocal<Integer> counter = new ThreadLocal<>();
                    counter.set(new Integer(0));
                    try {
                        List<Document> docs = getDocumentsFromFS(chunk);//grab a handful of documents
                        while (docs.size() > 0) {
                            for (Document d : docs)//process the documents we grabbed
                            {
                                //logger.debug("Processing document: " + d.toString());
                                postDocument(getDb(), getTb(), d);//post them up
                                counter.set(counter.get() + 1);
                            }
                            docs = getDocumentsFromFS(chunk);//grab another handful of documents
                        }
                        logger.info("Thread " + Thread.currentThread().getName() + " is done. It processed "
                                + counter.get() + " documents.");
                    } catch (IOException | ParseException e) {
                        logger.error("Couldn't read from document", e);
                    }
                }
            });
        }
    }

    //long start = new Date().getTime();
    StopWatch sw = new StopWatch();
    sw.start();
    //start your threads!
    for (Thread t : workers) {
        t.start();
    }
    logger.info("All threads started, waiting for completion.");
    boolean allDone = false;
    boolean first = true;
    while (!allDone || first) {
        first = false;
        boolean done = true;
        for (Thread t : workers) {
            if (t.isAlive()) {
                done = false;
                logger.info("Thread " + t.getName() + " is still running.");
                break;
            }
        }
        if (done) {
            allDone = true;
            sw.stop();
        } else {
            logger.info("We still have workers running...");
            Thread.sleep(5000);
        }
    }

    long miliseconds = sw.getTime();
    double seconds = (double) miliseconds / 1000d;
    output.info("Doc: Done loading data using: " + NUM_WORKERS + " and URL: " + BASE_URI + ". Took: " + seconds
            + " seconds");
    double tpms = (double) numDocs / (double) miliseconds;
    double tps = tpms * 1000;
    double transactionTime = (double) miliseconds / (double) numDocs;
    output.info(this.getDb().name() + " Doc: Average Transactions Per Second: " + tps);
    output.info(this.getDb().name() + " Doc: Average Transactions Time (in miliseconds): " + transactionTime);
    Thread.sleep(100000);//sleep a bit to let the DB digest that before trying anything else
}