Thursday, May 14, 2026

Class Level Locking in Java - inspired by Android's Asynctask implementation - serializing multiple threads...




After many months, I have opened my Java workspace and saw my implementation of Class Level locking used for thread serialization done more than a decade ago. This was inspired by Android's AsyncTask source code.

Here is the source code...

package com.somitsolutions.java.training.classlevellockingwithstaticnestedclass;



public class ExampleClass {

public ExampleClass(){

}

public static InnerNestedClass objInnerNestedClass = new InnerNestedClass();

static class InnerNestedClass{

public synchronized void testMethod(){

try {

for (int i = 0; i<10; i++){

System.out.println ("The testMethod for " + Thread.currentThread().getName() + " Object");

Thread.sleep(2000);

}

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}




package com.somitsolutions.java.training.classlevellockingwithstaticnestedclass;


public class R implements Runnable{

final ExampleClass exampleClassObject = new ExampleClass();

//final ExampleClass exampleClassObject2 = new ExampleClass();

public void run(){

exampleClassObject.objInnerNestedClass.testMethod();

}

}




package com.somitsolutions.java.training.classlevellockingwithstaticnestedclass;


public class Main {


public static void main(String[] args) {

// TODO Auto-generated method stub

R r1 = new R();

R r2 = new R();

Thread t1 = new Thread(r1);

Thread t2 = new Thread(r2);

t1.setName("Thread 1");

t2.setName("Thread 2");

t1.start();

t2.start();

}

}


1. What Exactly Is Happening Here?

We have:

public static InnerNestedClass objInnerNestedClass = new InnerNestedClass();

This line is the key.

Because the object is declared static, there is only one instance of InnerNestedClass for the entire JVM class ExampleClass.

No matter how many ExampleClass objects you create:

new ExampleClass();
new ExampleClass();
new ExampleClass();

they all share:

ExampleClass.objInnerNestedClass

There is exactly ONE monitor lock associated with that object.


2. Understanding the Synchronization

Inside the nested class:

public synchronized void testMethod()

This means:

synchronized(this)

So the lock is acquired on:

objInnerNestedClass

Since there is only ONE static instance:

public static InnerNestedClass objInnerNestedClass

all threads compete for the SAME monitor lock.


3. Flow of Execution

Step-by-step

You create:

R r1 = new R();
R r2 = new R();

Each R object creates its own:

final ExampleClass exampleClassObject = new ExampleClass();

So now you have:

  • Two different ExampleClass objects

  • BUT both point to the SAME static object

Conceptually:

ExampleClass Object A
        |
        ---> static objInnerNestedClass ----> [ONE OBJECT]

ExampleClass Object B
        |
        ---> static objInnerNestedClass ----> [SAME OBJECT]

4. What Happens When Threads Run?

Thread 1:

exampleClassObject.objInnerNestedClass.testMethod();

Thread 2:

exampleClassObject.objInnerNestedClass.testMethod();

Both are calling:

testMethod()

on the SAME shared object.

Since the method is synchronized:

public synchronized void testMethod()

only ONE thread can enter at a time.


5. Runtime Behavior

Suppose:

  • Thread 1 enters first

  • Thread 2 tries to enter

Then:

Thread 1 acquires monitor lock
Thread 2 BLOCKS

Thread 2 waits until:

Thread 1 exits testMethod()

Only then:

Thread 2 acquires lock

So output becomes SERIALIZED:

Thread 1 messages...
Thread 1 messages...
Thread 1 messages...

THEN

Thread 2 messages...
Thread 2 messages...

instead of interleaving.


6. Why This Is Called "Class-Level Locking"

Strictly speaking, true class-level locking is:

synchronized(ExampleClass.class)

or

public static synchronized void method()

which locks on the Class object itself.

But my example achieves a VERY SIMILAR EFFECT using:

static shared object + synchronized instance method

So effectively:

One shared lock for entire class

Hence, behaviorally, it becomes "class-wide serialization."


7. Why Static Matters

Without static:

public InnerNestedClass objInnerNestedClass

each ExampleClass object would get its OWN nested object.

Then:

Thread 1 -> Lock A
Thread 2 -> Lock B

No contention.

Both threads would run simultaneously.

So static is the entire reason serialization occurs.


8. Relationship to Android AsyncTask

In old Android implementations of Android AsyncTask, Google implemented task serialization using a very similar design.

Internally, AsyncTask had something conceptually similar to:

private static class SerialExecutor implements Executor {
    final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
    Runnable mActive;

    public synchronized void execute(final Runnable r) {
        ...
    }
}

and:

private static final SerialExecutor sDefaultExecutor
        = new SerialExecutor();

Notice the same pattern:


Shared Static Executor

private static final SerialExecutor sDefaultExecutor

ONE executor object for all AsyncTasks.


Synchronized Method

public synchronized void execute(...)

Only one thread could manipulate scheduling state at a time.


Result

Even if you created:

new MyAsyncTask().execute();
new MyAsyncTask().execute();
new MyAsyncTask().execute();

They were serialized through the SAME shared executor.

So tasks are executed one after another.

This was done to avoid:

  • race conditions

  • thread explosion

  • UI instability

  • uncontrolled parallelism

especially on low-memory mobile devices.


9. Why Android Did This

Early Android phones had:

  • very limited RAM

  • single-core CPUs

  • weak scheduling capabilities

If developers accidentally launched many background tasks simultaneously:

UI freezes
Battery drain
ANRs
Memory pressure

could happen.

So Android engineers intentionally serialized AsyncTasks.

Later Android versions introduced:

executeOnExecutor(THREAD_POOL_EXECUTOR)

to allow controlled parallelism.


10. Deeper JVM Insight

Every Java object has an associated:

Monitor Lock

When a synchronized instance method is called:

public synchronized void method()

JVM internally does roughly:

monitorenter(this)
...
monitorexit(this)

Since all threads share the SAME static object:

ONE monitor

becomes the synchronization bottleneck.


11. Why Studying Open Source Code Is Important

This is the most important part.

Reading open-source frameworks teaches things that textbooks usually cannot.

For example, from AsyncTask we learn:

  • real-world concurrency design

  • serialization strategies

  • thread scheduling

  • producer-consumer patterns

  • executor frameworks

  • synchronization tradeoffs


Theory vs Reality

A textbook may say:

"synchronized prevents race conditions"

But Android source code shows:

WHY engineers used synchronization
WHERE they used it
WHAT problem they were solving
WHAT tradeoffs they accepted

That is real engineering knowledge.


12. Why Great Engineers Read Source Code

Engineers who study frameworks like:

  • OpenJDK

  • Android

  • Linux kernel

  • OpenFOAM

  • FreeCAD

develop:

  • architectural thinking

  • systems intuition

  • debugging maturity

  • performance awareness

  • concurrency understanding

far beyond ordinary programming.


13. What You Are Actually Learning Here

My small example contains concepts from:

  • JVM monitor implementation

  • object lifetime

  • static memory model

  • synchronization semantics

  • concurrent scheduling

  • executor design

  • Android framework architecture

This is exactly why studying framework source code is powerful.

You stop seeing programming as:

"writing syntax"

and begin seeing it as:

"designing systems"

That transition is what separates an average coder from a strong software engineer.

Saturday, May 9, 2026

Walking Alone, Building Bharat: Why Intrinsic Motivation Defines the Future of Innovation


There comes a moment in every meaningful journey when a person realizes that leadership is not about applause, followers, or external validation. It is about conviction. It is about walking forward even when nobody accompanies you.

The timeless line from Ekla Chalo Re captures this spirit perfectly:

“If nobody responds to your call, then walk alone.”

This is not merely poetry. It is a philosophy of leadership.

A true leader does not wait for social approval before pursuing truth, innovation, or transformation. The ability to continue despite isolation is perhaps the deepest form of intrinsic motivation. History repeatedly shows that every major civilizational leap began with individuals willing to walk alone against convention.

Today, this mindset is becoming increasingly visible across India — or as many passionately call it, Bharat.

The Rise of a New Bharat

A profound transformation is underway.

For decades, elite education in India was concentrated in a few urban centers. But now, talent is emerging from Tier-2 and Tier-3 cities at an unprecedented scale. Access to knowledge is no longer geographically restricted.

The digital revolution has changed the equation.

Online education, open-source learning, recorded lectures from institutions like Indian Institutes of Technology, National Institutes of Technology, and other premier institutions are democratizing technical education.

The implications are enormous.

If a classroom of twenty students in a top engineering institution can produce two or three future entrepreneurs or researchers, what happens when world-class technical education reaches millions of students across the country through the internet?

The answer is simple:
India’s innovation capacity multiplies exponentially.

From Examination Factories to Knowledge Civilization

For years, one criticism often directed toward India was that the country produced service-sector engineers but lacked large-scale original research and deep technological innovation.

That narrative is beginning to change.

The future belongs to nations capable of producing:

  • researchers,

  • deep-tech innovators,

  • hardware engineers,

  • graphics programmers,

  • AI scientists,

  • simulation experts,

  • entrepreneurs,

  • and creators of foundational technology.

India’s growing ecosystem of online technical education, digital libraries, open-source software exposure, and accessible mentorship is slowly laying that foundation.

The next generation is not satisfied with merely consuming technology. They want to build it.

A Small Example of a Bigger Transformation

One of the most striking parts of this story is that the transformation is already visible at the school level.

My son, a Class 9 student, who began learning programming at the age of six. Over time, he explored multiple programming languages, including:

  • Java

  • Python

  • C++

Eventually, his interest moved toward advanced graphics programming using OpenGL.

But the remarkable aspect was not simply learning OpenGL.

Ridit reportedly went further by exposing a custom C++ OpenGL engine to Python using pybind11 — a concept normally encountered in advanced software engineering and systems programming.

This is significant because it reflects something deeper:
Young learners are no longer limiting themselves to textbook knowledge. They are beginning to understand interoperability, engine architecture, bindings, and real-world software ecosystems.

This is precisely how technological civilizations evolve.

The Internet Has Changed the Nature of Talent

In previous generations, access to elite knowledge depended heavily on geography, institutional privilege, or economic background.

Today, a motivated student with:

  • a computer,

  • internet access,

  • curiosity,

  • and discipline

can study subjects that were once accessible only to specialists.

From graphics programming to AI, from computational physics to simulation engineering, the barriers are steadily falling.

This democratization of technical capability may become one of the defining developments of 21st-century India.

Intrinsic Motivation: The Real National Resource

Natural resources matter.
Infrastructure matters.
Capital matters.

But civilizations ultimately rise through motivated human beings.

Intrinsic motivation — the inner drive to learn, create, solve problems, and pursue truth without external reward — is the invisible force behind every scientific and technological revolution.

A nation that cultivates intrinsically motivated students will eventually produce innovators.

And innovators create industries.
Industries create economic power.
Economic power creates strategic independence.

Walking Alone Before Others Join

Every new idea initially appears isolated.

Every breakthrough begins with a small number of believers.

The message is simple:
do not wait for universal approval before beginning meaningful work.

Whether in science, software, engineering, entrepreneurship, or national development, progress often starts with individuals willing to move forward before the crowd understands the direction.

That is leadership.

And perhaps that is the deeper meaning of “walk alone.”

Because eventually, if the path is true, others follow.

Jai Hind... Jai Bharat...