blob: d4a5d6caa68581636f1e0a8f951862891ff2ea14 [file] [log] [blame]
/*
* Copyright (c) 2015 Eike Stepper (Berlin, Germany) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eike Stepper - initial API and implementation
*/
package org.eclipse.net4j.util.concurrent;
import org.eclipse.net4j.util.StringUtil;
import org.eclipse.net4j.util.om.OMPlatform;
/**
* @author Eike Stepper
* @since 3.6
*/
public abstract class RunnableWithName implements Runnable
{
public static final boolean THREAD_NAMES = Boolean
.parseBoolean(OMPlatform.INSTANCE.getProperty("org.eclipse.net4j.util.thread.names", "false"));
public abstract String getName();
public final void run()
{
if (!THREAD_NAMES)
{
doRun();
return;
}
String name = getName();
if (StringUtil.isEmpty(name))
{
doRun();
return;
}
Thread thread = Thread.currentThread();
String oldName = thread.getName();
if (!StringUtil.isEmpty(oldName))
{
name = oldName + " - " + name;
}
thread.setName(name);
try
{
doRun();
}
finally
{
thread.setName(oldName);
}
}
protected abstract void doRun();
public static void runWithName(final String name, final Runnable runnable)
{
if (!THREAD_NAMES || StringUtil.isEmpty(name))
{
runnable.run();
return;
}
new RunnableWithName()
{
@Override
public String getName()
{
return name;
}
@Override
protected void doRun()
{
runnable.run();
}
}.run();
}
}