001: /* Threads.java
002:
003: {{IS_NOTE
004: Purpose:
005:
006: Description:
007:
008: History:
009: Sat Feb 21 23:12:06 2004, Created by tomyeh
010: }}IS_NOTE
011:
012: Copyright (C) 2003 Potix Corporation. All Rights Reserved.
013:
014: {{IS_RIGHT
015: This program is distributed under GPL Version 2.0 in the hope that
016: it will be useful, but WITHOUT ANY WARRANTY.
017: }}IS_RIGHT
018: */
019: package org.zkoss.lang;
020:
021: import org.zkoss.mesg.MCommon;
022: import org.zkoss.util.logging.Log;
023:
024: /**
025: * Thread relevant utilities.
026: *
027: * @author tomyeh
028: */
029: public class Threads {
030: private static final Log log = Log.lookup(Threads.class);
031:
032: /** Put the current thread to sleep for a while.
033: * @exception SystemException if it is interrupted.
034: * @since 3.0.0
035: */
036: public static final void sleep(int millisecs) {
037: try {
038: Thread.sleep(millisecs);
039: } catch (InterruptedException ex) {
040: throw SystemException.Aide.wrap(ex);
041: }
042: }
043:
044: /** Put the current thread to sleep for a while.
045: * @deprecated As of release 3.0.0, replaced by {@link #sleep}
046: */
047: public static final void pause(int millisecs) {
048: sleep(millisecs);
049: }
050:
051: /** Sets the priority without throwing any exception but log warning.
052: */
053: public static final void setPriority(Thread thd, int priority) {
054: try {
055: thd.setPriority(priority);
056: } catch (Exception ex) {
057: log.warningBriefly("Unable to change priority to "
058: + priority, ex);
059: }
060: }
061:
062: /** Sets the priority without throwing any exception but log warning.
063: */
064: public static final void setDaemon(Thread thd, boolean daemon) {
065: try {
066: thd.setDaemon(daemon);
067: } catch (Exception ex) {
068: log.warningBriefly("Unable to set DAEMON", ex);
069: }
070: }
071:
072: /** Waits a thread to die (and interrupt once a while)
073: * @param timeout how long to wait (0 means forever)
074: */
075: public static final void joinAndInterrupt(Thread thd, int timeout)
076: throws InterruptedException {
077: if (timeout == 0)
078: timeout = Integer.MAX_VALUE;
079:
080: final int PERIOD = 5000; //5 secs
081: for (int j = 0; timeout > 0; timeout -= PERIOD) {
082: thd.join(timeout > PERIOD ? PERIOD : timeout);
083: if (!thd.isAlive())
084: return; //done;
085:
086: try {
087: thd.interrupt(); //just in case
088: } catch (Throwable e2) { //ignore it
089: }
090:
091: if ((++j & 0x7) == 0)
092: log.info("Wait another thread to die over " + j
093: * PERIOD / 1000 + " seconds");
094: }
095: }
096:
097: /** A dummy function that is used to avoid compiler from optimizing
098: * statments around it.
099: */
100: public static final void dummy(Object o) {
101: new Integer(Objects.hashCode(o));
102: }
103: }
|