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

What Is Bitcoin?

Bitcoin is a decentralized digital currency that you can buy, sell and exchange directly, without an intermediary like a bank. Bitcoin’s creator, Satoshi Nakamoto, originally described the need for “an electronic payment system based on cryptographic proof instead of trust.” Each and every Bitcoin transaction that’s ever been made exists on a public ledger accessible to everyone, making transactions hard to reverse and difficult to fake. That’s by design: Core to their decentralized nature, Bitcoins aren’t backed by the government or any issuing institution, and there’s nothing to guarantee their value besides the proof baked in the heart of the system. “The reason why it’s worth money is simply because we, as people, decided it has value—same as gold,” says Anton Mozgovoy, co-founder & CEO of digital financial service company Holyheld.

How to Use Bitcoin?

n the U.S. people generally use Bitcoin as an alternative investment, helping diversify a portfolio apart from stocks and bonds. You can also use Bitcoin to make purchases, but the number of vendors that accept the cryptocurrency is still limited. Big companies that accept Bitcoin include Overstock, AT&T and Twitch. You may also find that some small local retailers or certain websites take Bitcoin, but you’ll have to do some digging. That said, PayPal has announced that it will enable cryptocurrency as a funding source for purchases this year, financing purchases by automatically converting crypto holdings to fiat currency for users. “They have 346 million users and they’re connected to 26 million merchants,” says Spencer Montgomery, founder of Uinta Crypto Consulting. “It’s huge.”

Java from sa


Telegram Java
FROM USA