Skip to content

XCOMMONS-3330: Job groups with several threads may not return a current job #1329

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@
*/
package org.xwiki.job;

import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.xwiki.component.annotation.Role;
import org.xwiki.stability.Unstable;

/**
* By default Jobs are either executed asynchronously whenever there is a free thread in the pool. Jobs can implement
Expand All @@ -40,9 +43,25 @@ public interface JobExecutor
*
* @param groupPath the group path
* @return the currently running job in the passed group
* @deprecated Use {@link #getCurrentJobs(JobGroupPath)} instead.
*/
@Deprecated(since = "17.4.0RC1")
Job getCurrentJob(JobGroupPath groupPath);

/**
* The set of jobs running within the specified job group.
*
* @param groupPath the path of the job group for which the current jobs should be retrieved
* @return a collection containing the currently running jobs in the provided group
* @since 17.4.0RC1
*/
@Unstable
default Collection<Job> getCurrentJobs(JobGroupPath groupPath)
{
// Not really accurate, but better than nothing.
return Collections.singleton(getCurrentJob(groupPath));
}

/**
* Return job corresponding to the provided id from the current executed or waiting jobs.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,15 @@
*/
package org.xwiki.job.internal;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
Expand Down Expand Up @@ -72,11 +78,12 @@ private class JobGroupExecutor extends JobThreadExecutor implements ThreadFactor

private final JobGroupPath path;

private Job currentJob;
private final Set<Job> currentJobs =
Collections.synchronizedSet(Collections.newSetFromMap(new IdentityHashMap<>()));

private String groupThreadName;
private final String groupThreadName;

private GroupedJobInitializer initializer;
private final GroupedJobInitializer initializer;

JobGroupExecutor(JobGroupPath path, GroupedJobInitializer initializer)
{
Expand All @@ -96,7 +103,7 @@ private class JobGroupExecutor extends JobThreadExecutor implements ThreadFactor
@Override
protected String getThreadName(Runnable r)
{
return this.groupThreadName + " - " + this.currentJob;
return this.groupThreadName + " - " + r;
}

@Override
Expand All @@ -110,7 +117,7 @@ protected void beforeExecute(Thread t, Runnable r)
{
DefaultJobExecutor.this.lockTree.lock(this.path);

this.currentJob = (Job) r;
this.currentJobs.add((Job) r);

super.beforeExecute(t, r);
}
Expand All @@ -120,22 +127,26 @@ protected void afterExecute(Runnable r, Throwable t)
{
DefaultJobExecutor.this.lockTree.unlock(this.path);

this.currentJob = null;
Job job = (Job) r;

super.afterExecute(r, t);
this.currentJobs.remove(job);

Job job = (Job) r;
super.afterExecute(r, t);

List<String> jobId = job.getRequest().getId();
if (jobId != null) {
synchronized (DefaultJobExecutor.this.groupedJobs) {
Queue<Job> jobQueue = DefaultJobExecutor.this.groupedJobs.get(jobId);
if (jobQueue != null) {
if (jobQueue.peek() == job) {
jobQueue.poll();
}
// Use compute() to synchronize on the job ID to avoid concurrent insertion/deletion by other threads.
DefaultJobExecutor.this.groupedJobs.compute(jobId, (k, v) -> {
if (v != null && v.peek() == job) {
v.poll();
}
}

if (v == null || v.isEmpty()) {
return null;
}

return v;
});
}
}

Expand Down Expand Up @@ -187,12 +198,13 @@ protected void afterExecute(Runnable r, Throwable t)

List<String> jobId = job.getRequest().getId();
if (jobId != null) {
synchronized (DefaultJobExecutor.this.jobs) {
Job storedJob = DefaultJobExecutor.this.jobs.get(jobId);
if (storedJob == job) {
DefaultJobExecutor.this.jobs.remove(jobId);
DefaultJobExecutor.this.jobs.computeIfPresent(jobId, (k, v) -> {
if (v == job) {
return null;
}
}

return v;
});
}

// Reset thread name since it's not used anymore
Expand Down Expand Up @@ -262,11 +274,23 @@ public void dispose() throws ComponentLifecycleException
// JobManager

@Override
public Job getCurrentJob(JobGroupPath path)
public Job getCurrentJob(JobGroupPath groupPath)
{
// Provide a default implementation so implementors of this interface can stop implementing this method.
return getCurrentJobs(groupPath).stream().findFirst().orElse(null);
}

@Override
public Collection<Job> getCurrentJobs(JobGroupPath path)
{
JobGroupExecutor executor = this.groupExecutors.get(path);

return executor != null ? executor.currentJob : null;
if (executor != null) {
// Return an unmodifiable copy of the set of currently running jobs.
return Collections.unmodifiableCollection(new ArrayList<>(executor.currentJobs));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not clear to me why you create an ArrayList. Isn't Collections.unmodifiableCollection enough to make the set readonly ?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to avoid that the collection updates when jobs are started or stopped. I would expect that we expose this method in a script service and I don't want to let the author of a Velocity script deal with the fact that directly after isEmpty() returns false, there might not be any elements anymore in the collection.

We could also let this return a List, this might make things more explicit what to expect in terms of the different operations?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to avoid that the collection updates when jobs are started or stopped.

Very good point indeed.

We could also let this return a List, this might make things more explicit what to expect in terms of the different operations?

Why not.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. I also found and fixed some issues in the implementations for constructing the list both in the default and in the actual implementation.

}

return Collections.emptyList();
}

@Override
Expand All @@ -281,10 +305,7 @@ public Job getJob(List<String> id)
// Is it in a group
Queue<Job> jobQueue = this.groupedJobs.get(id);
if (jobQueue != null) {
job = jobQueue.peek();
if (job != null) {
return job;
}
return jobQueue.peek();
}

return null;
Expand Down Expand Up @@ -324,8 +345,8 @@ public Job execute(String jobType, Request request) throws JobException
public void execute(Job job)
{
if (!this.disposed) {
if (job instanceof GroupedJob) {
executeGroupedJob((GroupedJob) job);
if (job instanceof GroupedJob groupedJob) {
executeGroupedJob(groupedJob);
} else {
executeSingleJob(job);
}
Expand All @@ -348,6 +369,8 @@ private void executeSingleJob(Job job)

private void executeGroupedJob(GroupedJob job)
{
// While synchronization isn't necessary for the insertion in the group executors, this ensures that jobs in
// the "groupedJobs" queues have the same order as in the executor's queue.
synchronized (this.groupExecutors) {
JobGroupPath path = job.getGroupPath();

Expand All @@ -358,26 +381,20 @@ private void executeGroupedJob(GroupedJob job)
return;
}

JobGroupExecutor groupExecutor = this.groupExecutors.get(path);

if (groupExecutor == null) {
groupExecutor =
new JobGroupExecutor(path, this.groupedJobInitializerManager.getGroupedJobInitializer(path));
this.groupExecutors.put(path, groupExecutor);
}
JobGroupExecutor groupExecutor = this.groupExecutors.computeIfAbsent(path,
p -> new JobGroupExecutor(p, this.groupedJobInitializerManager.getGroupedJobInitializer(p)));

groupExecutor.execute(job);

List<String> jobId = job.getRequest().getId();
if (jobId != null) {
synchronized (this.groupedJobs) {
Queue<Job> jobQueue = this.groupedJobs.get(jobId);
if (jobQueue == null) {
jobQueue = new ConcurrentLinkedQueue<>();
this.groupedJobs.put(jobId, jobQueue);
}
jobQueue.offer(job);
}
// Use compute() to synchronize on the job ID to prevent that another thread would remove the empty
// queue again.
this.groupedJobs.compute(jobId, (k, v) -> {
Queue<Job> queue = Objects.requireNonNullElseGet(v, ConcurrentLinkedQueue::new);
queue.offer(job);
return queue;
});
}
}
}
Expand Down