1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.issue.lbcore258;
15
16 import java.io.FileOutputStream;
17 import java.io.IOException;
18 import java.nio.channels.FileChannel;
19 import java.nio.channels.FileLock;
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 public class FileLockSimulator {
50
51 static String LINE_SEPARATOR = System.getProperty("line.separator");
52 static final int DOT_FREQ = 128;
53 static final int DOT_WITH_NEW_LINE_FREQ = DOT_FREQ * 80;
54
55 static String instanceName;
56 static int delay;
57 static FileOutputStream fos;
58 static FileChannel fileChannel;
59
60 public static void main(String[] args) throws IOException, InterruptedException {
61
62 String instanceName = args[0];
63 System.out.println("Instance named as [" + instanceName + "]");
64
65 String fileStr = args[1];
66 System.out.println("Output target specified as [" + fileStr + "]");
67
68 int delay = Integer.parseInt(args[2]);
69 System.out.println("Sleep delay specified as [" + delay + "] milliseconds");
70
71 fos = new FileOutputStream(fileStr, true);
72 fileChannel = fos.getChannel();
73
74 for (int i = 1;; i++) {
75 printDotAndSleep(i);
76 lockAndWrite(i);
77 }
78 }
79
80 static void lockAndWrite(int i) throws InterruptedException, IOException {
81 FileLock fileLock = null;
82 try {
83 fileLock = fileChannel.lock();
84 long position = fileChannel.position();
85 long size = fileChannel.size();
86 if (size != position) {
87 fileChannel.position(size);
88 }
89 String msg = "hello from" + instanceName + " " + i + LINE_SEPARATOR;
90 fos.write(msg.getBytes());
91 } finally {
92 if (fileLock != null) {
93 fileLock.release();
94 }
95 }
96 }
97
98 static void printDotAndSleep(int i) throws InterruptedException {
99 if (i % DOT_FREQ == 0) {
100 System.out.print(".");
101 Thread.sleep(delay);
102 }
103 if (i % DOT_WITH_NEW_LINE_FREQ == 0)
104 System.out.println("");
105 }
106 }