Skip to content

Instantly share code, notes, and snippets.

@ok3141
Last active August 29, 2015 14:10
Show Gist options
  • Save ok3141/c5bd4f1c59cc1d13defd to your computer and use it in GitHub Desktop.
Save ok3141/c5bd4f1c59cc1d13defd to your computer and use it in GitHub Desktop.
How to synchronize usage of stream providing direct reference on it? One of possible solutions
import java.io.PrintStream;
public class Sample {
public static final int COUNT = 10000;
public static void main(String[] args) {
final StreamHolder holder = new StreamHolder(System.out);
new Thread(new Runnable() {
@Override
public void run() {
threadOne(holder);
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
threadTwo(holder);
}
}).start();
}
private static void threadOne(StreamHolder holder) {
final SampleWorkerOne worker = new SampleWorkerOne();
for (int i = 0, n = COUNT; i < n; ++i) {
worker.head = "(my head " + i + ")";
worker.body = "(my body " + i + ")";
holder.doWithStream(worker);
sleep(20);
}
}
private static void threadTwo(StreamHolder holder) {
final SampleWorkerTwo worker = new SampleWorkerTwo();
for (int i = 0, n = COUNT; i < n; ++i) {
worker.buffer = "(my buffer " + i + ")";
holder.doWithStream(worker);
sleep(30);
}
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (Throwable ex) {
// ignore
}
}
}
interface StreamWorker {
void work(PrintStream out);
}
class StreamHolder {
private PrintStream mOut;
public StreamHolder(PrintStream out) {
mOut = out;
}
public synchronized void doWithStream(StreamWorker worker) {
worker.work(mOut);
}
}
class SampleWorkerOne implements StreamWorker {
String head;
String body;
@Override
public void work(PrintStream out) {
out.print("Head: ");
out.print(head);
out.print(" Body: ");
out.print(body);
out.print(" : ");
for (int i = 0, n = 20; i < n; ++i) {
out.print(i);
out.print('.');
}
out.println();
}
}
class SampleWorkerTwo implements StreamWorker {
String buffer;
@Override
public void work(PrintStream out) {
out.print("Buffer: ");
out.print(buffer);
out.print(" : ");
for (int i = 0, n = 20; i < n; ++i) {
out.print(i);
out.print('.');
}
out.println();
}
}
@ok3141
Copy link
Author

ok3141 commented Nov 26, 2014

This is example output without synchronized keyword:

Buffer: (my buffer 48) : 0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
Head: (my head 73) Body: (my body 73) : 0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
Head: (my head 74) Body: (my body 74) : 0.1.2.3.4.5.6.7.8.9.10Buffer: (my buffer 49) : .11.12.130.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18..14.15.16.1719..
18.19.
Head: (my head 75) Body: (my body 75) : 0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
Buffer: (my buffer 50) : 0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.
Head: (my head 76) Body: (my body 76) : 0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment