0% found this document useful (0 votes)
4 views6 pages

Java Concurrency Issues and Solutions

The document outlines various multithreading and concurrency issues in Java, including problems with producer-consumer patterns, singleton implementations, and synchronization pitfalls. It also addresses memory management concerns, such as memory leaks and misuse of finalize(), as well as immutability issues and pitfalls related to ThreadLocal and static variables. Additionally, it highlights common mistakes with locking, exceptions, and autoboxing in Java programming.

Uploaded by

haxid59003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views6 pages

Java Concurrency Issues and Solutions

The document outlines various multithreading and concurrency issues in Java, including problems with producer-consumer patterns, singleton implementations, and synchronization pitfalls. It also addresses memory management concerns, such as memory leaks and misuse of finalize(), as well as immutability issues and pitfalls related to ThreadLocal and static variables. Additionally, it highlights common mistakes with locking, exceptions, and autoboxing in Java programming.

Uploaded by

haxid59003
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

## Multithreading / Concurrency

### Broken Producer-Consumer


class SharedQueue { Queue queue = new LinkedList<>(); final int LIMIT = 10; public void produce()
throws InterruptedException { while (true) { if ([Link]() < LIMIT) { [Link](1); } } }
public void consume() throws InterruptedException { while (true) { if (![Link]()) {
[Link](); } } } }
■ No synchronization, race conditions, busy-waiting.
■ Use wait()/notifyAll() or BlockingQueue.

### Singleton with threading issue


public class Singleton { private static Singleton instance; public static Singleton
getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } }
■ Not thread-safe.
■ Use synchronized or double-checked locking with volatile.

### Synchronized on Mutable Object


class Counter { private Integer count = 0; public void increment() { synchronized (count) {
count++; } } }
■ Synchronizing on an object that is mutated breaks synchronization.
■ Use a separate final lock object.

### Volatile Misuse for Compound Action


class Flag { private volatile boolean initialized = false; public void init() { if
(!initialized) { // expensive init initialized = true; } } }
■ Compound actions aren't atomic.
■ Use synchronized or double-checked locking.

### Non-atomic Check-Then-Act


class Inventory { private int stock = 10; public boolean buyItem() { if (stock > 0) { stock--;
return true; } return false; } }
■ Not thread-safe.
■ Use synchronization or AtomicInteger.
## Memory / GC / Reference Handling
### Memory Leak with Listeners
class EventSource { private final List listeners = new ArrayList<>(); public void
registerListener(Listener l) { [Link](l); } }
■ Listeners never removed.
■ Use WeakReference or allow unregistration.

### Hidden Object Retention


class Cache { private Map heavyCache = new HashMap<>(); public void loadData(String key) {
[Link](key, new byte[100_000_000]); } }
■ Cache grows unbounded, risks OOM.
■ Use eviction strategy or bounded cache.

### finalize() Misuse


class MyResource { @Override protected void finalize() { [Link]("Cleaned up!"); } }
■ finalize() is deprecated and unreliable.
■ Use try-with-resources or Cleaner.
## Mutability / Immutability
### Broken Immutable Class
public class User { private final String name; private final List roles; public User(String
name, List roles) { [Link] = name; [Link] = roles; } public List getRoles() { return
roles; } }
■ Exposes mutable list.
■ Return unmodifiable copy using [Link]().

### Mutable Object as Map Key


class Person { String name; public Person(String name) { [Link] = name; } } Map map = new
HashMap<>(); Person p = new Person("Alice"); [Link](p, "Engineer"); [Link] = "Bob";
[Link]([Link](p));
■ Mutating key after inserting into map breaks lookup.
■ Use immutable keys.
## ThreadLocal / Static Pitfalls
### ThreadLocal Leaks in Web Servers
public class MyServlet { private static final ThreadLocal formatter = [Link](()
-> new SimpleDateFormat("yyyy-MM-dd")); public void doGet() { String today =
[Link]().format(new Date()); } }
■ ThreadLocal leaks if not removed in pooled threads.
■ Call [Link]() in finally block.

### Static Formatter Shared Across Threads


public class Formatter { private static final SimpleDateFormat format = new
SimpleDateFormat("yyyy-MM-dd"); public String format(Date date) { return [Link](date); }
}
■ SimpleDateFormat is not thread-safe.
■ Use DateTimeFormatter or ThreadLocal.
## Locking / Exceptions
### Swallowed InterruptedException
public void run() { try { [Link](1000); } catch (InterruptedException e) { // ignored } }
■ Interrupt signal lost.
■ Restore interrupt with [Link]().interrupt();

### Holding Lock Too Long


public synchronized void process() { long start = [Link](); while
([Link]() - start < 5000) { // do nothing } }
■ Lock held while busy-waiting.
■ Minimize time in synchronized blocks.
## Autoboxing / Primitives
### Autoboxing Pitfall
public class CompareIntegers { public static void main(String[] args) { Integer a = 1000;
Integer b = 1000; [Link](a == b); // ?? } }
■ `==` compares references.
■ Use .equals().

You might also like