The fastest way to prepare for Java multithreading questions is to climb a graded ladder: start with creating and joining threads, move to synchronization and visibility, then to executors and concurrent collections, and practise diagnosing broken code at every rung. This article gives you that ladder as a 14-day plan, a bug gallery of race conditions, and a set of question types that appear again and again in exams, interviews and internship tasks.
What Java multithreading questions actually test
Most questions fall into four families. Knowing the family tells you what the examiner wants.
- Definition questions: thread vs process,
RunnablevsThread, whatsynchronizedguarantees, whatvolatiledoes and does not do. - Output-prediction questions: a short program with two threads, and you decide which outputs are possible. The correct answer is often “it depends”, followed by the set of legal outputs.
- Bug-diagnosis questions: code that “usually works” but has a race, a deadlock or a visibility problem.
- Design tasks: build a producer-consumer pipeline, a thread-safe counter, a bounded cache or a parallel file processor.
A strong answer names the property at risk (atomicity, visibility, ordering), shows the failing interleaving, and then gives the smallest correct fix.
The three properties behind every concurrency bug
| Property | Meaning | Typical broken code | Typical fix |
|---|---|---|---|
| Atomicity | A compound action happens as one indivisible step | count++ on a shared int |
AtomicInteger, synchronized, or a lock |
| Visibility | A write by one thread becomes seen by others | A non-volatile boolean running flag |
volatile, or synchronization on both sides |
| Ordering | Operations are not reordered in a harmful way | Unsafe publication of an object | final fields, safe publication, happens-before edges |
Free 2-Week CareerSwami Internship
Online, 14 days, with a free offer letter and a free completion certificate once you finish the work. Check with your college that it fits your requirement before you enrol.
A graded exercise ladder from threads to concurrent collections
Work through the rungs in order. Do not move up until you can explain, without notes, why the previous rung’s fix works.
Rung 1: Creating, starting and joining threads
- Start three threads that each print their name five times. Run it ten times and note that the order changes.
- Replace
Threadsubclassing withRunnableand then a lambda. - Use
join()somainprints “done” only after all workers finish. - Explain what happens if you call
run()instead ofstart().
Rung 2: Shared state and the lost update
- Two threads each increment a shared counter 100,000 times. Print the final value and observe that it is usually below 200,000.
- Fix it with
synchronized, then withAtomicInteger, then withReentrantLock. - Write one sentence on when each fix is the better choice.
Rung 3: Visibility, volatile and interruption
- Write a worker that loops on a plain
booleanstop flag. Make it volatile and explain why that is enough here. - Show why
volatile int count; count++is still not safe. - Replace the flag with
Thread.interrupt()and handleInterruptedExceptioncorrectly by restoring the interrupt status when you cannot rethrow.
Rung 4: Coordination with wait, notify and blocking queues
- Build a producer-consumer with
wait()/notifyAll()inside awhileloop (never anif). - Rebuild it with
ArrayBlockingQueueand compare the code length and risk. - Add a poison-pill value so consumers shut down cleanly.
Rung 5: Executors, futures and thread pools
- Submit ten
Callable<Integer>tasks to a fixed pool of four threads and collect results from theFutureobjects. - Shut the pool down properly with
shutdown()andawaitTermination(). - Use
CompletableFuture.supplyAsyncto chain two steps, and handle an exception withexceptionally. - Explain why creating a new thread per task does not scale.
Rung 6: Concurrent collections and compound actions
- Replace a
HashMapshared by threads withConcurrentHashMap. - Implement a word-frequency counter using
mergeorcomputeIfAbsentinstead of check-then-put. - Compare
CopyOnWriteArrayListwith a synchronized list for a read-heavy listener list. - Use
CountDownLatchorSemaphorein a small simulation, such as a limited number of database connections.
A 14-day schedule that fits a two-week internship window
| Days | Focus | Output you should have |
|---|---|---|
| 1-2 | Rung 1 and thread lifecycle | Working programs plus a one-page lifecycle diagram |
| 3-4 | Rung 2, lost updates and locking | Three counter versions with timings |
| 5 | Rung 3, visibility and interruption | Stop-flag demo and an interrupt-safe worker |
| 6-7 | Rung 4, producer-consumer | Both the wait/notify and blocking-queue versions |
| 8-9 | Rung 5, executors and futures | A parallel task runner with clean shutdown |
| 10-11 | Rung 6, concurrent collections | Word counter and a bounded resource simulation |
| 12 | Bug gallery diagnosis | Written diagnosis of every bug below |
| 13 | Mini project | A small log-processing pipeline using a pool and a queue |
| 14 | Revision and mock questions | Spoken answers to the question bank, timed |
If you want a structured place to practise this alongside a deadline, the free two-week online internship from CareerSwami offers an offer letter and a completion certificate after successful completion, and its 14-day length matches this plan.
Bug gallery: eight race conditions to diagnose
All snippets below are illustrative and written for study. For each one, name the property at risk, describe a failing interleaving, and propose a fix before reading the answer key.
The specimens
// Bug 1: lost update
class Counter { int n; void inc() { n++; } }
// Bug 2: visibility
class Worker implements Runnable {
boolean running = true;
public void run() { while (running) { /* work */ } }
void stop() { running = false; }
}
// Bug 3: check-then-act on a map
if (!map.containsKey(k)) { map.put(k, compute(k)); } // map is ConcurrentHashMap
// Bug 4: lazy singleton
static Config inst;
static Config get() { if (inst == null) inst = new Config(); return inst; }
// Bug 5: wrong lock
class Acct {
private Integer bal = 0;
void add(int x) { synchronized (bal) { bal += x; } }
}
// Bug 6: deadlock
void transfer(Acct a, Acct b) {
synchronized (a) { synchronized (b) { /* move money */ } }
}
// Bug 7: wait with if
synchronized void take() throws InterruptedException {
if (queue.isEmpty()) wait();
return queue.remove();
}
// Bug 8: iterating a shared list
for (String s : sharedArrayList) { process(s); } // another thread adds items
Answer key
| Bug | Property at risk | Why it fails | Fix |
|---|---|---|---|
| 1 | Atomicity | n++ is read, add, write; two threads can read the same value |
AtomicInteger or synchronized method |
| 2 | Visibility | The worker may never see the write to running, so the loop can run forever |
Declare running volatile, or use interruption |
| 3 | Atomicity of a compound action | Each call is safe, but two threads can both pass the check | map.computeIfAbsent(k, this::compute) |
| 4 | Atomicity and safe publication | Two threads can create two instances, and another may see a partly built object | Initialization-on-demand holder, an enum singleton, or a volatile field with double-checked locking |
| 5 | Atomicity | bal += x boxes to a new Integer, so threads lock different objects |
Lock a private final object, or use AtomicInteger |
| 6 | Liveness | Thread 1 does transfer(a,b) while thread 2 does transfer(b,a); each holds one lock and waits for the other |
Acquire locks in a fixed global order, such as by account id |
| 7 | Correct condition checking | After a wakeup, another consumer may already have emptied the queue; spurious wakeups also occur | Use while instead of if |
| 8 | Safe iteration | A concurrent modification can throw ConcurrentModificationException or give inconsistent results |
CopyOnWriteArrayList, or copy under a lock before iterating |
Worked illustration: diagnosing a lost update step by step
This is an illustrative walk-through, not the output of an actual run. Take Bug 1 with n = 5 and two threads, A and B, each calling inc() once.
- Thread A reads
nand gets 5. - Thread B reads
nand also gets 5. - Thread A writes 6.
- Thread B writes 6.
Two increments happened, but the value rose by one. That is the failing interleaving, and writing it out like this is exactly what earns marks in a diagnosis question. The smallest fix is to change the field to AtomicInteger and call incrementAndGet(), which performs the read-modify-write as one atomic operation. A good follow-up sentence is: “Making the field volatile would not help, because volatile gives visibility but not atomicity of a compound action.”
On a real machine, a result lower than the expected total on a stress test with many iterations is likely, but it is not guaranteed on every run. That is why a passing test proves nothing about thread safety; reasoning about interleavings does.
Question bank for timed practice
Short conceptual questions
- What is the difference between
synchronizedon an instance method and on a static method? - Why does
wait()have to be called inside a synchronized block? - What does the happens-before relationship guarantee?
- When is
ConcurrentHashMapnot enough to keep your logic correct? - How does
shutdown()differ fromshutdownNow()?
Output-prediction and design tasks
- List every possible output of two threads that print “A” then “B” and “1” then “2” without synchronization.
- Design a thread-safe bounded cache and say which lock or collection you would use.
- Write a program that fetches ten simulated results in parallel and prints them in the original order.
- Explain how you would test a concurrent class, given that passing tests do not prove correctness.
Java multithreading prep for Vijayanagara Sri Krishnadevaraya University students
VSKU describes itself as a State University set up under the Karnataka State Universities Act 2000, and its campuses page says it is an affiliating university with about 100 affiliated colleges. In practice, this means your syllabus and exam pattern may depend on your programme and your college, so check what applies to you rather than assuming.
For computing students, the published syllabi are the best guide to what your written papers cover. The MCA syllabus is a 2-year, 4-semester programme effective 2024-25, with papers such as Data Structures (24MCA1C1L) carrying 30 internal assessment and 70 semester-exam marks, according to the excerpt. An M.Sc. Computer Science syllabus document from 2021 lists first-semester codes in the 21CSC series. These are excerpts, and syllabi get revised, so read the current version before planning. Whether a particular Java or concurrency topic appears in your paper has to be confirmed from the full document for your batch.
On the career side, the university’s Self Study Report (2022) says the Placement Cell supports career counselling and organises exclusive and pool campus recruitment. Multithreading questions are a common screening topic in Java interviews, so practising the ladder above is useful whatever the drive format. The same report mentions internship training in nearby industries by the Department of Chemistry, which is a departmental practice and not a university-wide rule. No university-wide rule on online internships was verified, so treat the following steps as your way to find out.
- Download the full syllabus PDF for your programme and search it for “Java”, “thread”, “concurrent” and “project”.
- Ask your department office, in writing, whether an online internship can count toward any project or training requirement, and keep the reply.
- Ask your head of department who sets internship rules for your college: the university or the college itself.
- Check the previous two years’ question papers for your Java paper to see how often threading appears.
- Ask the placement cell what the technical round format is, and whether concurrency is tested.
- Confirm exam and semester dates from the official notices on vskub.ac.in before fixing your 14-day window.
Habits that make the practice stick
- Write the interleaving before the fix. If you cannot show a failing order, you do not yet understand the bug.
- Prefer high-level tools. Reach for executors, blocking queues and concurrent collections before hand-written wait/notify.
- Keep shared mutable state small. Immutable objects and thread confinement remove whole categories of bugs.
- Always close pools. A forgotten
shutdown()keeps the JVM alive aftermainends. - Practise speaking. Explain each fix aloud in under 60 seconds, as you would in an interview.
Frequently Asked Questions
How long does it take to become comfortable with Java multithreading questions?
Two focused weeks are enough to handle common exam and interview questions if you code each rung of the ladder yourself. Deep mastery of memory-model subtleties takes longer and comes from repeated diagnosis practice.
Is volatile enough to make a counter thread-safe?
No. Volatile guarantees visibility, but count++ is still a read-modify-write sequence that can lose updates. Use AtomicInteger, a lock, or synchronized.
Should I learn wait and notify if executors exist?
Yes, for exams and interviews, because they are asked often and teach condition-based coordination. In real code, a BlockingQueue is usually the safer choice.
What is the difference between ConcurrentHashMap and a synchronized HashMap?
ConcurrentHashMap allows concurrent reads and updates with finer-grained internal coordination, while a synchronized wrapper locks the whole map per call. Neither makes a check-then-put sequence atomic, so use methods like computeIfAbsent and merge.
How do I prove my multithreaded code is correct?
Testing alone cannot prove it, because races appear only under particular timings. Argue correctness from invariants, locks and happens-before relationships, and use stress tests only as extra evidence.
Will my VSKU syllabus include concurrency topics?
That depends on your programme and batch. Open the current syllabus PDF for your course and search for threading or concurrency topics, and ask your department if a unit title is unclear.
Can an online internship count for credit at my college?
That is not confirmed for VSKU in general. CareerSwami’s internship comes with a free offer letter and a free completion certificate, but it does not promise academic credit, so ask your department in writing whether it is recognised for any requirement.
What should I do when a deadlock appears in my practice code?
Take a thread dump with jstack or your IDE, find the threads blocked on each other’s locks, and fix the lock ordering so every thread acquires locks in the same sequence.
Related Java & Enterprise Software guides
- University of Gour Banga Students: Using Free Resources to Prepare for a Java Internship
- Puducherry Technological University: Understanding Application Logging and Monitoring as a Java Intern
- North East Adventist University Students: Teamwork Habits for Your First Java Project Team
- All Java & Enterprise Software internship guides
Ready to put this into practice?
Join the free two-week CareerSwami online internship in Java & Enterprise Software. The internship, the offer letter and the completion certificate are free.




