Telegram Group & Telegram Channel
🧠 Java-задача: "Immutable? Не совсем…"

📜 Условие:

У тебя есть якобы *immutable* класс:


public class Point {
public final int x;
public final int y;

public Point(int x, int y) {
this.x = x;
this.y = y;
}
}


И следующий код:


public class Main {
static Point shared;

public static void main(String[] args) throws InterruptedException {
Thread writer = new Thread(() -> {
shared = new Point(1, 2);
});

Thread reader = new Thread(() -> {
Point p = shared;
if (p != null) {
System.out.println("x = " + p.x + ", y = " + p.y);
}
});

writer.start();
writer.join();
reader.start();
reader.join();
}
}


Вопрос:

1. Могут ли быть выведены "x = 1, y = 0" или даже "x = 0, y = 0"?
2. Почему? x и y ведь final — разве этого недостаточно?
3. Как гарантировать корректность и видимость всех полей в многопоточной среде?

⚠️ Подвох:

- В Java Memory Model (`JMM`) даже `final` поля не дают полной гарантии видимости, если объект передаётся между потоками без синхронизации.
- Поток reader может увидеть частично сконструированный объект:
- Конструктор не завершился, а shared уже указывает на объект.
- Это не баг JVM, а результат слабых гарантий JMM без синхронизации.

Правильный ответ:

Да, такой результат возможенreader может увидеть x = 1, y = 0, или даже x = 0, y = 0.

🛡️ Как защититься:

- Сделать shared volatile, или
- Передавать объект через synchronized блоки, Lock, AtomicReference, CountDownLatch, Thread-safe очередь, и т.д.


static volatile Point shared;


🎯 Чему учит задача:

• Знание Java Memory Model (JMM)
• Понимание, что final != synchronized
• Почему даже "immutable" объекты могут стать "опасно mutating"
• Умение писать багоустойчивый многопоточный код

@javatg



tg-me.com/javatg/1855
Create:
Last Update:

🧠 Java-задача: "Immutable? Не совсем…"

📜 Условие:

У тебя есть якобы *immutable* класс:


public class Point {
public final int x;
public final int y;

public Point(int x, int y) {
this.x = x;
this.y = y;
}
}


И следующий код:


public class Main {
static Point shared;

public static void main(String[] args) throws InterruptedException {
Thread writer = new Thread(() -> {
shared = new Point(1, 2);
});

Thread reader = new Thread(() -> {
Point p = shared;
if (p != null) {
System.out.println("x = " + p.x + ", y = " + p.y);
}
});

writer.start();
writer.join();
reader.start();
reader.join();
}
}


Вопрос:

1. Могут ли быть выведены "x = 1, y = 0" или даже "x = 0, y = 0"?
2. Почему? x и y ведь final — разве этого недостаточно?
3. Как гарантировать корректность и видимость всех полей в многопоточной среде?

⚠️ Подвох:

- В Java Memory Model (`JMM`) даже `final` поля не дают полной гарантии видимости, если объект передаётся между потоками без синхронизации.
- Поток reader может увидеть частично сконструированный объект:
- Конструктор не завершился, а shared уже указывает на объект.
- Это не баг JVM, а результат слабых гарантий JMM без синхронизации.

Правильный ответ:

Да, такой результат возможенreader может увидеть x = 1, y = 0, или даже x = 0, y = 0.

🛡️ Как защититься:

- Сделать shared volatile, или
- Передавать объект через synchronized блоки, Lock, AtomicReference, CountDownLatch, Thread-safe очередь, и т.д.


static volatile Point shared;


🎯 Чему учит задача:

• Знание Java Memory Model (JMM)
• Понимание, что final != synchronized
• Почему даже "immutable" объекты могут стать "опасно mutating"
• Умение писать багоустойчивый многопоточный код

@javatg

BY Java


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/javatg/1855

View MORE
Open in Telegram


Java Telegram | DID YOU KNOW?

Date: |

Telegram today rolling out an update which brings with it several new features.The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. The update also adds interactive emoji. When you send one of the select animated emoji in chat, you can now tap on it to initiate a full screen animation. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations. This is then visible to you or anyone else who's also present in chat at the moment. The animations are also accompanied by vibrations.

Pinterest (PINS) Stock Sinks As Market Gains

Pinterest (PINS) closed at $71.75 in the latest trading session, marking a -0.18% move from the prior day. This change lagged the S&P 500's daily gain of 0.1%. Meanwhile, the Dow gained 0.9%, and the Nasdaq, a tech-heavy index, lost 0.59%. Heading into today, shares of the digital pinboard and shopping tool company had lost 17.41% over the past month, lagging the Computer and Technology sector's loss of 5.38% and the S&P 500's gain of 0.71% in that time. Investors will be hoping for strength from PINS as it approaches its next earnings release. The company is expected to report EPS of $0.07, up 170% from the prior-year quarter. Our most recent consensus estimate is calling for quarterly revenue of $467.87 million, up 72.05% from the year-ago period.

Java from kr


Telegram Java
FROM USA