Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Implements Executors.schedule with delay, better messaging in AjaxUrlConnection #183

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Dec 3, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified sources/net.sf.j2s.core/dist/swingjs/SwingJS-site.zip
Binary file not shown.
2 changes: 1 addition & 1 deletion sources/net.sf.j2s.core/dist/swingjs/timestamp
Original file line number Diff line number Diff line change
@@ -1 +1 @@
20201203093348
20201203153534
Binary file modified sources/net.sf.j2s.core/dist/swingjs/ver/3.2.9/SwingJS-site.zip
Binary file not shown.
2 changes: 1 addition & 1 deletion sources/net.sf.j2s.core/dist/swingjs/ver/3.2.9/timestamp
Original file line number Diff line number Diff line change
@@ -1 +1 @@
20201203093348
20201203153534
Binary file modified sources/net.sf.j2s.java.core/dist/SwingJS-site.zip
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@

package java.util.concurrent;
import java.util.concurrent.atomic.*;

import swingjs.JSToolkit;

import java.util.*;

/**
Expand Down Expand Up @@ -156,62 +159,63 @@ public class ScheduledThreadPoolExecutor
private static final AtomicLong sequencer = new AtomicLong(0);

/**
* Returns current nanosecond time.
* Returns current millisecond time.
*/
final long now() {
return System.nanoTime();
final long nowms() {
return System.currentTimeMillis();
// return System.nanoTime();
}

private class ScheduledFutureTask<V>
extends FutureTask<V> implements RunnableScheduledFuture<V> {

/** Sequence number to break ties FIFO */
private final long sequenceNumber;
/** The time the task is enabled to execute in nanoTime units */
private long time;
/** The time the task is enabled to execute in MilliTime units */
private long timems;
/**
* Period in nanoseconds for repeating tasks. A positive
* Period in milliseconds for repeating tasks. A positive
* value indicates fixed-rate execution. A negative value
* indicates fixed-delay execution. A value of 0 indicates a
* non-repeating task.
*/
private final long period;
private final long periodms;

/** The actual task to be re-enqueued by reExecutePeriodic */
RunnableScheduledFuture<V> outerTask = this;

/**
* Creates a one-shot action with given nanoTime-based trigger time.
* Creates a one-shot action with given milliTime-based trigger time.
*/
ScheduledFutureTask(Runnable r, V result, long ns) {
ScheduledFutureTask(Runnable r, V result, long ms) {
super(r, result);
this.time = ns;
this.period = 0;
this.timems = ms;
this.periodms = 0;
this.sequenceNumber = sequencer.getAndIncrement();
}

/**
* Creates a periodic action with given nano time and period.
* Creates a periodic action with given milli time and period.
*/
ScheduledFutureTask(Runnable r, V result, long ns, long period) {
ScheduledFutureTask(Runnable r, V result, long ms, long period) {
super(r, result);
this.time = ns;
this.period = period;
this.timems = ms;
this.periodms = period;
this.sequenceNumber = sequencer.getAndIncrement();
}

/**
* Creates a one-shot action with given nanoTime-based trigger.
* Creates a one-shot action with given milliTime-based trigger.
*/
ScheduledFutureTask(Callable<V> callable, long ns) {
super(callable);
this.time = ns;
this.period = 0;
this.timems = ns;
this.periodms = 0;
this.sequenceNumber = sequencer.getAndIncrement();
}

public long getDelay(TimeUnit unit) {
long d = unit.convert(time - now(), TimeUnit.NANOSECONDS);
long d = unit.convert(timems - nowms(), TimeUnit.MILLISECONDS);
return d;
}

Expand All @@ -220,7 +224,7 @@ public int compareTo(Delayed other) {
return 0;
if (other instanceof ScheduledFutureTask) {
ScheduledFutureTask<?> x = (ScheduledFutureTask<?>)other;
long diff = time - x.time;
long diff = timems - x.timems;
if (diff < 0)
return -1;
else if (diff > 0)
Expand All @@ -230,8 +234,8 @@ else if (sequenceNumber < x.sequenceNumber)
else
return 1;
}
long d = (getDelay(TimeUnit.NANOSECONDS) -
other.getDelay(TimeUnit.NANOSECONDS));
long d = (getDelay(TimeUnit.MILLISECONDS) -
other.getDelay(TimeUnit.MILLISECONDS));
return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
}

Expand All @@ -241,18 +245,18 @@ else if (sequenceNumber < x.sequenceNumber)
* @return true if periodic
*/
public boolean isPeriodic() {
return period != 0;
return periodms != 0;
}

/**
* Sets the next time to run for a periodic task.
*/
private void setNextRunTime() {
long p = period;
long p = periodms;
if (p > 0)
time += p;
timems += p;
else
time = now() - p;
timems = nowms() - p;
}

/**
Expand Down Expand Up @@ -283,6 +287,7 @@ boolean canRunInCurrentRunState(boolean periodic) {
executeExistingDelayedTasksAfterShutdown);
}

Map<Integer, RunnableScheduledFuture<?>> todo = new HashMap<>();
/**
* Main execution method for delayed or periodic tasks. If pool is shut down,
* rejects the task. Otherwise adds task to queue and starts a thread, if
Expand All @@ -304,7 +309,13 @@ private void delayedExecute(RunnableScheduledFuture<?> task) {

if (/** @j2sNative true || */
false) {
new Thread(task).start();
int[] id = new int[1];
todo.put(id[0] = JSToolkit.dispatch(new Thread(() -> {
RunnableScheduledFuture<?> me = todo.remove(id[0]);
if (me != null)
task.run();
}), Math.max(-1, (int) task.getDelay(TimeUnit.MILLISECONDS)), 0), task);

} else /** @j2sIgnore */
{
super.getQueue().add(task);
Expand Down Expand Up @@ -402,7 +413,7 @@ protected <V> RunnableScheduledFuture<V> decorateTask(
* @throws IllegalArgumentException if {@code corePoolSize < 0}
*/
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.MILLISECONDS,
new DelayedWorkQueue());
}

Expand All @@ -419,7 +430,7 @@ public ScheduledThreadPoolExecutor(int corePoolSize) {
*/
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.MILLISECONDS,
new DelayedWorkQueue(), threadFactory);
}

Expand All @@ -436,7 +447,7 @@ public ScheduledThreadPoolExecutor(int corePoolSize,
*/
public ScheduledThreadPoolExecutor(int corePoolSize,
RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.MILLISECONDS,
new DelayedWorkQueue(), handler);
}

Expand All @@ -457,7 +468,7 @@ public ScheduledThreadPoolExecutor(int corePoolSize,
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.MILLISECONDS,
new DelayedWorkQueue(), threadFactory, handler);
}

Expand All @@ -467,7 +478,7 @@ public ScheduledFuture<?> schedule(Runnable command,
if (command == null || unit == null)
throw new NullPointerException();
if (delay < 0) delay = 0;
long triggerTime = now() + unit.toNanos(delay);
long triggerTime = nowms() + unit.toMillis(delay);
RunnableScheduledFuture<?> t = decorateTask(command,
new ScheduledFutureTask<Void>(command, null, triggerTime));
delayedExecute(t);
Expand All @@ -480,7 +491,7 @@ public <V> ScheduledFuture<V> schedule(Callable<V> callable,
if (callable == null || unit == null)
throw new NullPointerException();
if (delay < 0) delay = 0;
long triggerTime = now() + unit.toNanos(delay);
long triggerTime = nowms() + unit.toMillis(delay);
RunnableScheduledFuture<V> t = decorateTask(callable,
new ScheduledFutureTask<V>(callable, triggerTime));
delayedExecute(t);
Expand All @@ -496,12 +507,12 @@ public ScheduledFuture<?> scheduleAtFixedRate(Runnable command,
if (period <= 0)
throw new IllegalArgumentException();
if (initialDelay < 0) initialDelay = 0;
long triggerTime = now() + unit.toNanos(initialDelay);
long triggerTime = nowms() + unit.toMillis(initialDelay);
ScheduledFutureTask<Void> sft =
new ScheduledFutureTask<Void>(command,
null,
triggerTime,
unit.toNanos(period));
unit.toMillis(period));
RunnableScheduledFuture<Void> t = decorateTask(command, sft);
sft.outerTask = t;
delayedExecute(t);
Expand All @@ -517,12 +528,12 @@ public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
if (delay <= 0)
throw new IllegalArgumentException();
if (initialDelay < 0) initialDelay = 0;
long triggerTime = now() + unit.toNanos(initialDelay);
long triggerTime = nowms() + unit.toMillis(initialDelay);
ScheduledFutureTask<Void> sft =
new ScheduledFutureTask<Void>(command,
null,
triggerTime,
unit.toNanos(-delay));
unit.toMillis(-delay));
RunnableScheduledFuture<Void> t = decorateTask(command, sft);
sft.outerTask = t;
delayedExecute(t);
Expand Down Expand Up @@ -550,22 +561,22 @@ public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command,
* @throws NullPointerException {@inheritDoc}
*/
public void execute(Runnable command) {
schedule(command, 0, TimeUnit.NANOSECONDS);
schedule(command, 0, TimeUnit.MILLISECONDS);
}

// Override AbstractExecutorService methods

public Future<?> submit(Runnable task) {
return schedule(task, 0, TimeUnit.NANOSECONDS);
return schedule(task, 0, TimeUnit.MILLISECONDS);
}

public <T> Future<T> submit(Runnable task, T result) {
return schedule(Executors.callable(task, result),
0, TimeUnit.NANOSECONDS);
0, TimeUnit.MILLISECONDS);
}

public <T> Future<T> submit(Callable<T> task) {
return schedule(task, 0, TimeUnit.NANOSECONDS);
return schedule(task, 0, TimeUnit.MILLISECONDS);
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,14 +69,17 @@ protected AjaxURLConnection(URL url) {

private Object ajax;
Object info;
private String statusText;

@Override
public String getHeaderField(String name) {
try {
if (getResponseCode() != -1) {
@SuppressWarnings("unused")
Object info = this.info;
return /**
* @j2sNative this.info && this.info.xhr &&
* this.info.xhr.getResponseHeader(name) ||
* @j2sNative info && info.xhr &&
* info.xhr.getResponseHeader(name) ||
*/
null;
}
Expand All @@ -92,9 +95,10 @@ public Map<String, List<String>> getHeaderFields() {
try {
if (getResponseCode() != -1) {
String[] data = null;
Object info = this.info;
/**
* @j2sNative data = this.info && this.info.xhr &&
* this.info.xhr.getAllResponseHeaders(); data && (data =
* @j2sNative data = info && info.xhr &&
* info.xhr.getAllResponseHeaders(); data && (data =
* data.trim().split("\n"));
*/
// ["content-length: 996"
Expand Down Expand Up @@ -254,6 +258,7 @@ private void setJQueryResponseCodeFromJQuery(Object result) {
* result[1] == 10); if (isEmpty) result = new Int8Array;
*/

statusText = /** @j2sNative info.xhr.statusText || */"";
responseCode = (!isEmpty ? /** @j2sNative info.xhr.status || */
0 : getAJAXStatusError());
}
Expand All @@ -262,7 +267,7 @@ private int getAJAXStatusError() {
@SuppressWarnings("unused")
Object info = this.info;
// AJAX cannot distinguish among a network connection error, a method (PUT) error, or a file not found
return /** @j2sNative !info.xhr.statusText || (info.xhr.statusText+"").indexOf("NetworkError:") == 0 ? 400 : */HTTP_NOT_FOUND;
return /** @j2sNative info.xhr.status > 0 ? info.xhr.status : !info.xhr.statusText || (info.xhr.statusText+"").indexOf("NetworkError:") == 0 ? 400 : */HTTP_NOT_FOUND;
}

private String getFileDocumentDir() {
Expand Down Expand Up @@ -406,8 +411,13 @@ public InputStream getInputStream() throws IOException {
return is;
responseCode = -1;
is = getInputStreamAndResponse(false);
switch (responseCode) {

}
if (responseCode == HTTP_BAD_REQUEST) {
throw new UnknownHostException(url.toString());
throw new java.net.UnknownHostException(url.toString());
} else if (responseCode > HTTP_BAD_REQUEST && responseCode != 404) {
throw new IOException("Server returned HTTP response code: " + responseCode + " for URL: " + url);
}
if (is == null)
throw new FileNotFoundException("opening " + url);
Expand Down
Loading