📄 hsqltimer.java
字号:
/** * Retrieves the instant in time just before this task was * last executed by the background thread. A value of zero * indicates that this task has never been executed. * * @return the last time this task was executed or zero if never */ synchronized long getLastScheduled() { return last; } /** * Retrieves the time at which this task is next scheduled for * execution. * * @return the time at which this task is next scheduled for * execution */ synchronized long getNextScheduled() { return next; } /** * Updates the last and next scheduled execution times. * * @param last when this task was last executed * @param next when this task is to be next executed */ synchronized void updateSchedule(final long last, final long next) { this.last = last; this.next = next; } /** * Sets the new periodicity of this task in milliseconds. <p> * * If this task is cancelled or the new period is identical to the * current period, then this invocation has essentailly no effect * and this object is returned. <p> * * Otherwise, if the new period is greater than the current period, then * a simple field assignment occurs and this object is returned. <p> * * If none of the previous cases hold, then this task is cancelled and * a new, equivalent task with the new period is scheduled for * immediate first execution and returned to the caller. <p> * * @param period the new period * @return a task reference, as per the rules stated above. */ synchronized Object setPeriod(final long newPeriod) { if (this.period == newPeriod || this.isCancelled()) { return this; } else if (newPeriod > this.period) { this.period = newPeriod; return this; } else { this.cancel(); return HsqlTimer.this.addTask(now(), this.runnable, newPeriod, this.relative); } } } /** * Heap-based priority queue. * * Provides extensions to facilitate and simplify implementing * timer functionality. */ protected static class TaskQueue extends HsqlArrayHeap { /** * Constructs a new TaskQueue with the specified initial capacity and * ObjectComparator. * * @param capacity the initial capacity of the queue * @param oc The ObjectComparator this queue uses to maintain its * Heap invariant. */ TaskQueue(final int capacity, final ObjectComparator oc) { super(capacity, oc); } /** * Type-safe add method. <p> * * Can be used to inject debugging or accounting behaviour. <p> * * @param task the task to add */ void addTask(final Task task) { // System.out.println("task added: " + task); super.add(task); } /** * Atomically removes all tasks in this queue and then and cancels * them. */ void cancelAllTasks() { Object[] oldHeap; int oldCount; synchronized (this) { oldHeap = this.heap; oldCount = this.count; // 1 instead of 0 to avoid unintended aoob exceptions this.heap = new Object[1]; this.count = 0; } for (int i = 0; i < oldCount; i++) { ((Task) oldHeap[i]).cancelled = true; } } /** * Causes the calling thread to wait until another thread invokes * {@link #unpark() unpark} or the specified amount of time has * elapsed. * * Implements the sync & wait(n) half of this queue's availability * condition. <p> * * @param timeout the maximum time to wait in milliseconds. * @throws java.lang.InterruptedException if another thread has * interrupted the current thread. The <i>interrupted status</i> of * the current thread is cleared when this exception is thrown. */ synchronized void park(final long timeout) throws InterruptedException { this.wait(timeout); } /** * Retrieves the head of this queue, without removing it. <p> * * This method has the side-effect of removing tasks from the * head of this queue until a non-cancelled task is encountered * or this queue is empty. <p> * * If this queue is initially empty or is emptied in the process * of finding the earliest scheduled non-cancelled task, * then null is returned. <p> * * @return the earliest scheduled non-cancelled task, or null if no such * task exists */ synchronized Task peekTask() { while (super.heap[0] != null && ((Task) super.heap[0]).isCancelled()) { super.remove(); } return (Task) super.heap[0]; } /** * Informs this queue that the given task is supposedly cancelled. <p> * * If the indicated task is identical to the current head of * this queue, then it is removed and this queue is * {@link #unpark() unparked}. <p> * * The cancelled status of the given task is not verified; it is * assumed that the caller is well-behaved (always passes a * non-null reference to a cancelled task). * * @param task a supposedly cancelled task */ synchronized void signalTaskCancelled(Task task) { // We only care about the case where HsqlTimer.nextTask // might be parked momentarily on this task. if (task == super.heap[0]) { super.remove(); this.notify(); } } /** * Type-safe remove method. <p> * * Removes the head task from this queue. <p> * * Can be used to inject debugging or accounting behaviour. <p> * * @return this queue's head task or null if no such task exists */ Task removeTask() { // System.out.println("removing task..."); return (Task) super.remove(); } /** * Wakes up a single thread (if any) that is waiting on this queue's * {@link #park(long) park} method. * * Implements the sync & notify half of this queue's availability * condition. */ synchronized void unpark() { this.notify(); } }// ---------------------------------- tests ------------------------------------// /**// * Computes the system-specific average {@link java.io.FileDescriptor#sync()// * sync} time. <p>// *// * @param runs iterations to perform when computing the average// * @param buff the data to write before each sync call// * @return the total time to write buff and call sync runs times,// * divided by runs// */// static double avgSyncTime(int runs, byte[] buff) {// java.io.File file = null;// java.io.FileOutputStream fos;// java.io.FileDescriptor fd;// long start = System.currentTimeMillis();//// try {// file = java.io.File.createTempFile("SyncTest", ".tmp");// fos = new java.io.FileOutputStream(file);// fd = fos.getFD();//// for (int i = 0; i < runs; i++) {// fos.write(buff);// fos.flush();// fd.sync();// }//// long elapsed = System.currentTimeMillis() - start;//// return (elapsed/(double)runs);// } catch (Exception e) {// throw new RuntimeException(e);// } finally {// if (file != null) {// file.delete();// }// }// }//// /**// * WRITE_DELAY simulation task.// *// * Writes a given buffer to disk, sync's the associated file// * descriptor and maintains an account of the average period// * between executions.// */// static class WriteAndSyncTask extends java.util.TimerTask {// // static// /** Used to make the name of each task unique. */// static int serial;// /** The data to write. */// static final byte[] buf = new byte[256];//// // instance// /** Identifes this task. */// String name;// /** The time at which this task was last executed. */// long last;// /** A running sum of the periods between executions. */// long total;// /** The number of times this task has been executed. */// int runs;// /** True until this task is the first time. */// boolean firstTime = true;// /** The file to write. */// java.io.File file;// /** The FileOutputStream to write. */// java.io.FileOutputStream fos;// /** The FileDescriptor to sync. */// java.io.FileDescriptor fd;//// /** Constructs a new WriteAndSyncTask */// WriteAndSyncTask() {// this.name = "Task." + serial++;//// try {// this.file = java.io.File.createTempFile(name, ".tmp");// this.fos = new java.io.FileOutputStream(file);// this.fd = fos.getFD();// } catch(java.io.IOException ioe) {// throw new RuntimeException(ioe);// }// }//// /**// * Runnable implementation. <p>// *// * Does the average period accounting and// * invokes the writeAndSync method.// */// public void run() {// final long now = System.currentTimeMillis();//// if (this.firstTime) {// this.firstTime = false;// } else {// this.total += (now - this.last);// }//// this.last = now;//// writeAndSync();//// this.runs++;// }//// /**// * Writes a given buffer to disk and syncs the associated file// * descriptor.// */// void writeAndSync() {// try {// this.fos.write(buf);// this.fos.flush();// this.fd.sync();// Thread.sleep(1);// } catch(Exception e) {// e.printStackTrace();// }// }//// /**// * Closes the FileOutputStream, deletes the file// * and nullifies Object fields.// */// public void release() {// try {// this.fos.close();// } catch(Exception e) {// e.printStackTrace();// }// try {// this.file.delete();// } catch (Exception e) {// e.printStackTrace();// }//// this.fos = null;// this.file = null;// this.fd = null;// }//// /**// * Retrieves the computed moment of actual average periodicity// * experienced by this task.// */// public float getAveragePeriod() {// return (this.runs < 2) ? Float.NaN// : (this.total/(float)(this.runs - 1));// }////// /**// * @return the String representation of this task, indicating// * its name, the number of runs so far and the
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -