@Test public void testAddItem() throws Exception { assertTimeout(ofMillis(10000), () -> { final Inventory inventory = new Inventory(INVENTORY_SIZE); final ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT); for (int i = 0; i < THREAD_COUNT; i++) { executorService.execute(() -> { while (inventory.addItem(new Item())) { } ; }); } executorService.shutdown(); executorService.awaitTermination(5, TimeUnit.SECONDS); final List<Item> items = inventory.getItems(); assertNotNull(items); assertEquals(INVENTORY_SIZE, items.size()); assertEquals(INVENTORY_SIZE, appender.getLogSize()); for (int i = 0; i < items.size(); i++) { assertTrue(appender.log.get(i).getFormattedMessage().contains("items.size()=" + (i + 1))); } }); }
public boolean addItem(Item item) { if (items.size() < inventorySize) { lock.lock(); try { if (items.size() < inventorySize) { items.add(item); LOGGER.info("{}: items.size()={}, inventorySize={}", Thread.currentThread(), items.size(), inventorySize); return true; } } finally { lock.unlock(); } } return false; }
Inventory { public boolean addItem(Item item) { if (items.size() < inventorySize) { lock.lock(); try { if (items.size() < inventorySize) { items.add(item); LOGGER.info("{}: items.size()={}, inventorySize={}", Thread.currentThread(), items.size(), inventorySize); return true; } } finally { lock.unlock(); } } return false; } }
Inventory { public boolean addItem(Item item) { if (items.size() < inventorySize) { lock.lock(); try { if (items.size() < inventorySize) { items.add(item); LOGGER.info("{}: items.size()={}, inventorySize={}", Thread.currentThread(), items.size(), inventorySize); return true; } } finally { lock.unlock(); } } return false; } Inventory(int inventorySize); }
Inventory { public boolean addItem(Item item) { if (items.size() < inventorySize) { lock.lock(); try { if (items.size() < inventorySize) { items.add(item); LOGGER.info("{}: items.size()={}, inventorySize={}", Thread.currentThread(), items.size(), inventorySize); return true; } } finally { lock.unlock(); } } return false; } Inventory(int inventorySize); boolean addItem(Item item); final List<Item> getItems(); }
Inventory { public boolean addItem(Item item) { if (items.size() < inventorySize) { lock.lock(); try { if (items.size() < inventorySize) { items.add(item); LOGGER.info("{}: items.size()={}, inventorySize={}", Thread.currentThread(), items.size(), inventorySize); return true; } } finally { lock.unlock(); } } return false; } Inventory(int inventorySize); boolean addItem(Item item); final List<Item> getItems();  }