1 package com.github.davidmoten.rx2.internal;
2
3 import java.util.concurrent.TimeUnit;
4 import java.util.regex.Matcher;
5 import java.util.regex.Pattern;
6
7 import io.reactivex.Scheduler;
8 import io.reactivex.disposables.Disposable;
9
10 public final class SchedulerWithId extends Scheduler {
11
12 private final Scheduler scheduler;
13 private final String id;
14 private final static Pattern pattern = Pattern.compile("\\bschedId=\\[[^\\]]+\\]+\\b");
15
16 public SchedulerWithId(Scheduler scheduler, String id) {
17 this.scheduler = scheduler;
18 this.id = "[" + id + "]";
19 }
20
21 @Override
22 public Worker createWorker() {
23
24 final Worker worker = scheduler.createWorker();
25 Worker w = new Worker() {
26
27 @Override
28 public Disposable schedule(final Runnable action, long delayTime, TimeUnit unit) {
29 Runnable a = new Runnable() {
30 @Override
31 public void run() {
32 String name = null;
33 try {
34 name = setThreadName();
35 action.run();
36 } finally {
37 if (name != null) {
38 Thread.currentThread().setName(name);
39 }
40 }
41 }
42 };
43 return worker.schedule(a, delayTime, unit);
44 }
45
46 @Override
47 public void dispose() {
48 worker.dispose();
49 }
50
51 @Override
52 public boolean isDisposed() {
53 return worker.isDisposed();
54 }
55
56 };
57 return w;
58
59 }
60
61 private String setThreadName() {
62 String name = Thread.currentThread().getName();
63 String newName = updateNameWithId(name, id);
64 Thread.currentThread().setName(newName);
65 return name;
66 }
67
68 private static String updateNameWithId(String name, String id) {
69 final String newName;
70 if (name == null) {
71 newName = id;
72 } else {
73 Matcher matcher = pattern.matcher(name);
74 if (matcher.find()) {
75 newName = name.replace(matcher.group(), "schedId=" + id);
76 } else {
77 newName = name + "|schedId=" + id;
78 }
79 }
80 return newName;
81 }
82
83 }