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: |

Spiking bond yields driving sharp losses in tech stocks

A spike in interest rates since the start of the year has accelerated a rotation out of high-growth technology stocks and into value stocks poised to benefit from a reopening of the economy. The Nasdaq has fallen more than 10% over the past month as the Dow has soared to record highs, with a spike in the 10-year US Treasury yield acting as the main catalyst. It recently surged to a cycle high of more than 1.60% after starting the year below 1%. But according to Jim Paulsen, the Leuthold Group's chief investment strategist, rising interest rates do not represent a long-term threat to the stock market. Paulsen expects the 10-year yield to cross 2% by the end of the year. A spike in interest rates and its impact on the stock market depends on the economic backdrop, according to Paulsen. Rising interest rates amid a strengthening economy "may prove no challenge at all for stocks," Paulsen said.

Why Telegram?

Telegram has no known backdoors and, even though it is come in for criticism for using proprietary encryption methods instead of open-source ones, those have yet to be compromised. While no messaging app can guarantee a 100% impermeable defense against determined attackers, Telegram is vulnerabilities are few and either theoretical or based on spoof files fooling users into actively enabling an attack.

Java from fr


Telegram Java
FROM USA