use of java.lang.Thread.UncaughtExceptionHandler in project j2objc by google.
the class ForkJoinPool method registerWorker.
// Registering and deregistering workers
/**
* Callback from ForkJoinWorkerThread to establish and record its
* WorkQueue. To avoid scanning bias due to packing entries in
* front of the workQueues array, we treat the array as a simple
* power-of-two hash table using per-thread seed as hash,
* expanding as needed.
*
* @param wt the worker thread
* @return the worker's queue
*/
final WorkQueue registerWorker(ForkJoinWorkerThread wt) {
UncaughtExceptionHandler handler;
WorkQueue[] ws;
int s, ps;
wt.setDaemon(true);
if ((handler = ueh) != null)
wt.setUncaughtExceptionHandler(handler);
do {
} while (!U.compareAndSwapInt(this, INDEXSEED, s = indexSeed, s += SEED_INCREMENT) || // skip 0
s == 0);
WorkQueue w = new WorkQueue(this, wt, mode, s);
if (((ps = plock) & PL_LOCK) != 0 || !U.compareAndSwapInt(this, PLOCK, ps, ps += PL_LOCK))
ps = acquirePlock();
int nps = (ps & SHUTDOWN) | ((ps + PL_LOCK) & ~SHUTDOWN);
try {
if ((ws = workQueues) != null) {
// skip if shutting down
int n = ws.length, m = n - 1;
// use odd-numbered indices
int r = (s << 1) | 1;
if (ws[r &= m] != null) {
// collision
// step by approx half size
int probes = 0;
int step = (n <= 4) ? 2 : ((n >>> 1) & EVENMASK) + 2;
while (ws[r = (r + step) & m] != null) {
if (++probes >= n) {
workQueues = ws = Arrays.copyOf(ws, n <<= 1);
m = n - 1;
probes = 0;
}
}
}
w.poolIndex = (short) r;
// volatile write orders
w.eventCount = r;
ws[r] = w;
}
} finally {
if (!U.compareAndSwapInt(this, PLOCK, ps, nps))
releasePlock(nps);
}
wt.setName(workerNamePrefix.concat(Integer.toString(w.poolIndex >>> 1)));
return w;
}
use of java.lang.Thread.UncaughtExceptionHandler in project j2objc by google.
the class ThreadTest method test_get_setDefaultUncaughtExceptionHandler.
/**
* @tests java.lang.Thread#getDefaultUncaughtExceptionHandler
* @tests java.lang.Thread#setDefaultUncaughtExceptionHandler
*/
public void test_get_setDefaultUncaughtExceptionHandler() {
class Handler implements UncaughtExceptionHandler {
public void uncaughtException(Thread thread, Throwable ex) {
}
}
final Handler handler = new Handler();
Thread.setDefaultUncaughtExceptionHandler(handler);
assertSame(handler, Thread.getDefaultUncaughtExceptionHandler());
Thread.setDefaultUncaughtExceptionHandler(null);
assertNull(Thread.getDefaultUncaughtExceptionHandler());
//TODO add security-based tests
}
use of java.lang.Thread.UncaughtExceptionHandler in project java-design-patterns by iluwatar.
the class BallThreadTest method testInterrupt.
/**
* Verify if the {@link BallThread} is interruptible
*/
@Test(timeout = 5000)
public void testInterrupt() throws Exception {
final BallThread ballThread = new BallThread();
final UncaughtExceptionHandler exceptionHandler = mock(UncaughtExceptionHandler.class);
ballThread.setUncaughtExceptionHandler(exceptionHandler);
ballThread.setTwin(mock(BallItem.class));
ballThread.start();
ballThread.interrupt();
ballThread.join();
verify(exceptionHandler).uncaughtException(eq(ballThread), any(RuntimeException.class));
verifyNoMoreInteractions(exceptionHandler);
}
use of java.lang.Thread.UncaughtExceptionHandler in project guava by hceylan.
the class LocalLoadingCacheTest method testRecursiveComputation.
public void testRecursiveComputation() throws InterruptedException {
final AtomicReference<LoadingCache<Integer, String>> cacheRef = new AtomicReference<LoadingCache<Integer, String>>();
CacheLoader<Integer, String> recursiveLoader = new CacheLoader<Integer, String>() {
@Override
public String load(Integer key) {
if (key > 0) {
return key + ", " + cacheRef.get().getUnchecked(key - 1);
} else {
return "0";
}
}
};
LoadingCache<Integer, String> recursiveCache = new CacheBuilder<Integer, String>().weakKeys().weakValues().build(recursiveLoader);
cacheRef.set(recursiveCache);
assertEquals("3, 2, 1, 0", recursiveCache.getUnchecked(3));
recursiveLoader = new CacheLoader<Integer, String>() {
@Override
public String load(Integer key) {
return cacheRef.get().getUnchecked(key);
}
};
recursiveCache = new CacheBuilder<Integer, String>().weakKeys().weakValues().build(recursiveLoader);
cacheRef.set(recursiveCache);
// tells the test when the compution has completed
final CountDownLatch doneSignal = new CountDownLatch(1);
Thread thread = new Thread() {
@Override
public void run() {
try {
cacheRef.get().getUnchecked(3);
} finally {
doneSignal.countDown();
}
}
};
thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
}
});
thread.start();
boolean done = doneSignal.await(1, TimeUnit.SECONDS);
if (!done) {
StringBuilder builder = new StringBuilder();
for (StackTraceElement trace : thread.getStackTrace()) {
builder.append("\tat ").append(trace).append('\n');
}
fail(builder.toString());
}
}
use of java.lang.Thread.UncaughtExceptionHandler in project MinecraftForge by MinecraftForge.
the class SplashProgress method start.
public static void start() {
File configFile = new File(Minecraft.getMinecraft().mcDataDir, "config/splash.properties");
File parent = configFile.getParentFile();
if (!parent.exists())
parent.mkdirs();
FileReader r = null;
config = new Properties();
try {
r = new FileReader(configFile);
config.load(r);
} catch (IOException e) {
FMLLog.info("Could not load splash.properties, will create a default one");
} finally {
IOUtils.closeQuietly(r);
}
//Some system do not support this and have weird effects so we need to detect and disable by default.
//The user can always force enable it if they want to take the responsibility for bugs.
//For now macs derp so disable them.
boolean defaultEnabled = !System.getProperty("os.name").toLowerCase().contains("mac");
// Enable if we have the flag, and there's either no optifine, or optifine has added a key to the blackboard ("optifine.ForgeSplashCompatible")
// Optifine authors - add this key to the blackboard if you feel your modifications are now compatible with this code.
enabled = getBool("enabled", defaultEnabled) && ((!FMLClientHandler.instance().hasOptifine()) || Launch.blackboard.containsKey("optifine.ForgeSplashCompatible"));
rotate = getBool("rotate", false);
showMemory = getBool("showMemory", true);
logoOffset = getInt("logoOffset", 0);
backgroundColor = getHex("background", 0xFFFFFF);
fontColor = getHex("font", 0x000000);
barBorderColor = getHex("barBorder", 0xC0C0C0);
barColor = getHex("bar", 0xCB3D35);
barBackgroundColor = getHex("barBackground", 0xFFFFFF);
memoryGoodColor = getHex("memoryGood", 0x78CB34);
memoryWarnColor = getHex("memoryWarn", 0xE6E84A);
memoryLowColor = getHex("memoryLow", 0xE42F2F);
final ResourceLocation fontLoc = new ResourceLocation(getString("fontTexture", "textures/font/ascii.png"));
final ResourceLocation logoLoc = new ResourceLocation(getString("logoTexture", "textures/gui/title/mojang.png"));
final ResourceLocation forgeLoc = new ResourceLocation(getString("forgeTexture", "fml:textures/gui/forge.png"));
final ResourceLocation forgeFallbackLoc = new ResourceLocation("fml:textures/gui/forge.png");
File miscPackFile = new File(Minecraft.getMinecraft().mcDataDir, getString("resourcePackPath", "resources"));
FileWriter w = null;
try {
w = new FileWriter(configFile);
config.store(w, "Splash screen properties");
} catch (IOException e) {
FMLLog.log(Level.ERROR, e, "Could not save the splash.properties file");
} finally {
IOUtils.closeQuietly(w);
}
miscPack = createResourcePack(miscPackFile);
if (!enabled)
return;
// getting debug info out of the way, while we still can
FMLCommonHandler.instance().registerCrashCallable(new ICrashCallable() {
public String call() throws Exception {
return "' Vendor: '" + glGetString(GL_VENDOR) + "' Version: '" + glGetString(GL_VERSION) + "' Renderer: '" + glGetString(GL_RENDERER) + "'";
}
public String getLabel() {
return "GL info";
}
});
CrashReport report = CrashReport.makeCrashReport(new Throwable() {
@Override
public String getMessage() {
return "This is just a prompt for computer specs to be printed. THIS IS NOT A ERROR";
}
@Override
public void printStackTrace(final PrintWriter s) {
s.println(getMessage());
}
@Override
public void printStackTrace(final PrintStream s) {
s.println(getMessage());
}
}, "Loading screen debug info");
System.out.println(report.getCompleteReport());
try {
d = new SharedDrawable(Display.getDrawable());
Display.getDrawable().releaseContext();
d.makeCurrent();
} catch (LWJGLException e) {
e.printStackTrace();
disableSplash(e);
}
//Call this ASAP if splash is enabled so that threading doesn't cause issues later
getMaxTextureSize();
//Thread mainThread = Thread.currentThread();
thread = new Thread(new Runnable() {
private final int barWidth = 400;
private final int barHeight = 20;
private final int textHeight2 = 20;
private final int barOffset = 55;
public void run() {
setGL();
fontTexture = new Texture(fontLoc, null);
logoTexture = new Texture(logoLoc, null, false);
forgeTexture = new Texture(forgeLoc, forgeFallbackLoc);
glEnable(GL_TEXTURE_2D);
fontRenderer = new SplashFontRenderer();
glDisable(GL_TEXTURE_2D);
while (!done) {
ProgressBar first = null, penult = null, last = null;
Iterator<ProgressBar> i = ProgressManager.barIterator();
while (i.hasNext()) {
if (first == null)
first = i.next();
else {
penult = last;
last = i.next();
}
}
glClear(GL_COLOR_BUFFER_BIT);
// matrix setup
int w = Display.getWidth();
int h = Display.getHeight();
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(320 - w / 2, 320 + w / 2, 240 + h / 2, 240 - h / 2, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
// mojang logo
setColor(backgroundColor);
glEnable(GL_TEXTURE_2D);
logoTexture.bind();
glBegin(GL_QUADS);
logoTexture.texCoord(0, 0, 0);
glVertex2f(320 - 256, 240 - 256);
logoTexture.texCoord(0, 0, 1);
glVertex2f(320 - 256, 240 + 256);
logoTexture.texCoord(0, 1, 1);
glVertex2f(320 + 256, 240 + 256);
logoTexture.texCoord(0, 1, 0);
glVertex2f(320 + 256, 240 - 256);
glEnd();
glDisable(GL_TEXTURE_2D);
// memory usage
if (showMemory) {
glPushMatrix();
glTranslatef(320 - (float) barWidth / 2, 20, 0);
drawMemoryBar();
glPopMatrix();
}
// bars
if (first != null) {
glPushMatrix();
glTranslatef(320 - (float) barWidth / 2, 310, 0);
drawBar(first);
if (penult != null) {
glTranslatef(0, barOffset, 0);
drawBar(penult);
}
if (last != null) {
glTranslatef(0, barOffset, 0);
drawBar(last);
}
glPopMatrix();
}
angle += 1;
// forge logo
setColor(backgroundColor);
float fw = (float) forgeTexture.getWidth() / 2;
float fh = (float) forgeTexture.getHeight() / 2;
if (rotate) {
float sh = Math.max(fw, fh);
glTranslatef(320 + w / 2 - sh - logoOffset, 240 + h / 2 - sh - logoOffset, 0);
glRotatef(angle, 0, 0, 1);
} else {
glTranslatef(320 + w / 2 - fw - logoOffset, 240 + h / 2 - fh - logoOffset, 0);
}
int f = (angle / 5) % forgeTexture.getFrames();
glEnable(GL_TEXTURE_2D);
forgeTexture.bind();
glBegin(GL_QUADS);
forgeTexture.texCoord(f, 0, 0);
glVertex2f(-fw, -fh);
forgeTexture.texCoord(f, 0, 1);
glVertex2f(-fw, fh);
forgeTexture.texCoord(f, 1, 1);
glVertex2f(fw, fh);
forgeTexture.texCoord(f, 1, 0);
glVertex2f(fw, -fh);
glEnd();
glDisable(GL_TEXTURE_2D);
// We use mutex to indicate safely to the main thread that we're taking the display global lock
// So the main thread can skip processing messages while we're updating.
// There are system setups where this call can pause for a while, because the GL implementation
// is trying to impose a framerate or other thing is occurring. Without the mutex, the main
// thread would delay waiting for the same global display lock
mutex.acquireUninterruptibly();
Display.update();
// As soon as we're done, we release the mutex. The other thread can now ping the processmessages
// call as often as it wants until we get get back here again
mutex.release();
if (pause) {
clearGL();
setGL();
}
Display.sync(100);
}
clearGL();
}
private void setColor(int color) {
glColor3ub((byte) ((color >> 16) & 0xFF), (byte) ((color >> 8) & 0xFF), (byte) (color & 0xFF));
}
private void drawBox(int w, int h) {
glBegin(GL_QUADS);
glVertex2f(0, 0);
glVertex2f(0, h);
glVertex2f(w, h);
glVertex2f(w, 0);
glEnd();
}
private void drawBar(ProgressBar b) {
glPushMatrix();
// title - message
setColor(fontColor);
glScalef(2, 2, 1);
glEnable(GL_TEXTURE_2D);
fontRenderer.drawString(b.getTitle() + " - " + b.getMessage(), 0, 0, 0x000000);
glDisable(GL_TEXTURE_2D);
glPopMatrix();
// border
glPushMatrix();
glTranslatef(0, textHeight2, 0);
setColor(barBorderColor);
drawBox(barWidth, barHeight);
// interior
setColor(barBackgroundColor);
glTranslatef(1, 1, 0);
drawBox(barWidth - 2, barHeight - 2);
// slidy part
setColor(barColor);
// Step can sometimes be 0.
drawBox((barWidth - 2) * (b.getStep() + 1) / (b.getSteps() + 1), barHeight - 2);
// progress text
String progress = "" + b.getStep() + "/" + b.getSteps();
glTranslatef(((float) barWidth - 2) / 2 - fontRenderer.getStringWidth(progress), 2, 0);
setColor(fontColor);
glScalef(2, 2, 1);
glEnable(GL_TEXTURE_2D);
fontRenderer.drawString(progress, 0, 0, 0x000000);
glPopMatrix();
}
private void drawMemoryBar() {
int maxMemory = bytesToMb(Runtime.getRuntime().maxMemory());
int totalMemory = bytesToMb(Runtime.getRuntime().totalMemory());
int freeMemory = bytesToMb(Runtime.getRuntime().freeMemory());
int usedMemory = totalMemory - freeMemory;
float usedMemoryPercent = usedMemory / (float) maxMemory;
glPushMatrix();
// title - message
setColor(fontColor);
glScalef(2, 2, 1);
glEnable(GL_TEXTURE_2D);
fontRenderer.drawString("Memory Used / Total", 0, 0, 0x000000);
glDisable(GL_TEXTURE_2D);
glPopMatrix();
// border
glPushMatrix();
glTranslatef(0, textHeight2, 0);
setColor(barBorderColor);
drawBox(barWidth, barHeight);
// interior
setColor(barBackgroundColor);
glTranslatef(1, 1, 0);
drawBox(barWidth - 2, barHeight - 2);
// slidy part
long time = System.currentTimeMillis();
if (usedMemoryPercent > memoryColorPercent || (time - memoryColorChangeTime > 1000)) {
memoryColorChangeTime = time;
memoryColorPercent = usedMemoryPercent;
}
int memoryBarColor;
if (memoryColorPercent < 0.75f) {
memoryBarColor = memoryGoodColor;
} else if (memoryColorPercent < 0.85f) {
memoryBarColor = memoryWarnColor;
} else {
memoryBarColor = memoryLowColor;
}
setColor(memoryLowColor);
glPushMatrix();
glTranslatef((barWidth - 2) * (totalMemory) / (maxMemory) - 2, 0, 0);
drawBox(2, barHeight - 2);
glPopMatrix();
setColor(memoryBarColor);
drawBox((barWidth - 2) * (usedMemory) / (maxMemory), barHeight - 2);
// progress text
String progress = getMemoryString(usedMemory) + " / " + getMemoryString(maxMemory);
glTranslatef(((float) barWidth - 2) / 2 - fontRenderer.getStringWidth(progress), 2, 0);
setColor(fontColor);
glScalef(2, 2, 1);
glEnable(GL_TEXTURE_2D);
fontRenderer.drawString(progress, 0, 0, 0x000000);
glPopMatrix();
}
private String getMemoryString(int memory) {
return StringUtils.leftPad(Integer.toString(memory), 4, ' ') + " MB";
}
private void setGL() {
lock.lock();
try {
Display.getDrawable().makeCurrent();
} catch (LWJGLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
glClearColor((float) ((backgroundColor >> 16) & 0xFF) / 0xFF, (float) ((backgroundColor >> 8) & 0xFF) / 0xFF, (float) (backgroundColor & 0xFF) / 0xFF, 1);
glDisable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
private void clearGL() {
Minecraft mc = Minecraft.getMinecraft();
mc.displayWidth = Display.getWidth();
mc.displayHeight = Display.getHeight();
mc.resize(mc.displayWidth, mc.displayHeight);
glClearColor(1, 1, 1, 1);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_ALPHA_TEST);
glAlphaFunc(GL_GREATER, .1f);
try {
Display.getDrawable().releaseContext();
} catch (LWJGLException e) {
e.printStackTrace();
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
});
thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
FMLLog.log(Level.ERROR, e, "Splash thread Exception");
threadError = e;
}
});
thread.start();
checkThreadState();
}
Aggregations