import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; /** * Test writing to disk by multiple threads all contending over the synchronized lock ... */ public class TestSynchLockContention_J7 { public static void main(String[] args) throws IOException, InterruptedException { try ( ContendedResource resource = new ContendedResource("outfile.txt") ) { int contenderCount = Integer.parseInt(args[0]); int usageCount = Integer.parseInt(args[1]); int linesPerUse = Integer.parseInt(args[2]); List contenders = new ArrayList<>(contenderCount); long start = System.currentTimeMillis(); for (int i = 0; i < contenderCount; i++) { Contender worker = new Contender(resource, linesPerUse, usageCount); contenders.add(worker); worker.start(); } for (Contender contender : contenders) { contender.join(); } long end = System.currentTimeMillis(); System.out.println("" + contenders.size() + " threads wrote total of " + resource.getBytecount() + " bytes in " + (end - start) + "ms."); } } private static class ContendedResource implements AutoCloseable { private long bytecount = 0; private PrintWriter out; public ContendedResource(String filename) throws IOException { File outfile = new File("outfile.txt"); out = new PrintWriter(new FileWriter(outfile)); } public synchronized long useResource(long lineslong) { for ( int i=0; i